您的位置:首页 > 其它

单链表(一):如何实现单链表的创建、测长、遍历

2015-10-20 10:20 369 查看
示例代码如下:

#include<iostream>
using namespace std;

///单链表结构体:结点
typedef struct student
{
int data;				//结点中的数据
struct student *next;	//指向链表下一个结点的指针
}node;

node *head;	//头结点指针

///建立单链表
void *create()
{
node *p,*s;	//增加结点的位置指针、要增加结点的指针
int x,cycle=1;		//x是结点中的数据,若为0代表创建结束;cycle是循环控制变量
head=(node*)malloc(sizeof(node)); //动态分配,建立头节点
p=head;
while(cycle)
{
printf("Please input the data:");
scanf("%d",&x);
if(x!=0)
{
s=(node*)malloc(sizeof(node));	//动态分配,每次新建一个节点
s->data=x;						//将数据存入该结点
//			printf("%d\n",s->data);			//查看该结点中的数据是否正确
p->next=s;						//连接头指针与当前结点
p=s;							//并将头指针指向当前结点的指针,即下一个结点的地址
}
else
{
cycle=0;
}
}

p->next=NULL;		//最后一个结点为空指针(必须)

//	head=head->next;	//创建完毕单链表,头结点指针回去
//	printf("\n   yyy   %d",head->data);	//打印第一个结点中的数据,用于验证

return head;		//返回根结点
}

///遍历单链表(单链表打印),同时测长
//注:链表无法从反方向进行遍历
void traverse(node *head)
{
node *p;
int index=0;
if(head->next==NULL)
{
printf("Link is empty!\n");
return;
}
p=head->next;
while(p!=NULL)//遍历链表
{
printf("The %dth node is:%d\n",++index,p->data);//打印元素,亦可计算链表长度(index)
p=p->next;//进入下一个结点
}
printf("\n该链表长度为:%d\n\n",index);
}

int main()
{
cout<<"/***** 单链表的创建 *****/"<<endl;
create();		//单链表的创建

cout<<endl<<"/***** 单链表的遍历与测长 *****/"<<endl;
traverse(head);	//单链表的遍历与测长

return 0;
}


测试结果如下图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息