您的位置:首页 > 理论基础 > 数据结构算法

数据结构——1 单链表建立、输出和测长

2016-08-18 16:37 399 查看

单链表——建立、输出和测长

创建单链表,并输出链表,查找链表中某个结点元素,测试链表的长度(结点个数)。

链表操作中一种习惯是将头结点作为第一个结点,另一种是头结点起标记作用,它后面的结点作为第一个结点,个人喜好这种方式,个人。

#include<iostream>
using namespace std;
struct node       //node结构体,里面有一个node指针,用来指向下一个node对象
{
int x;
node *next;   //指向什么类型的对象,就用什么类型的指针
};

node* create(int n)         //创建链表,参数n表示结点的个数,返回类型是结点指针node*
{
node *head=new node;    //建立头结点
node *p=head;           //创建用于往后指的node指针

for(int i=0;i<n;i++)
{
node *temp=new node;     //new一个node指针
temp->x=rand()%100;
p->next=temp;            //将p的next指向创建的temp,把新节点连接到链表后面
p=temp;                  //将p指向新结点temp,即p移动到下一个节点
}
p->next=NULL;                //创建完成后,p->next指向NULL

return head;
}

int getLength(node *head)        //求链表的长度,参数head表示链表的头结点,返回值是链表的长度,即结点个数
{
node *p;
p=head->next;                //p重新指向头结点后的那个结点,即for循环创建的第一个结点
int len=0;

while(p!=NULL)
{
len++;
p=p->next;
}

return len;                  //返回链表结点个数,链表长度
}

void display(node *head)         //输出链表
{
node *p;
p=head->next;                //p重新指向头结点后的那个结点,即for循环创建的第一个结点
if(p==NULL)
cout<<"NULL List";
while(p!=NULL)               //输出
{
cout<<p->x<<"  ";
p=p->next;
}
cout<<endl;
}

node* search(node *head,int pos)
{
node *p;
p=head->next;                //p重新指向头结点后的那个结点,即for循环创建的第一个结点

while(--pos)                 //查找,不能用pos--
{
if((p=p->next)==NULL)
{
cout<<"incorrect position"<<endl;
break;
}

}

if(p!=NULL)
cout<<p->x<<endl;
return p;
}

int main()
{
node *list;
list=create(10);
display(list);
cout<<"The length of list is: "<<getLength(list)<<endl;
search(list,1);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息