您的位置:首页 > 其它

单链表的一些细节

2016-07-21 00:00 218 查看
摘要: 单链表

去年的秋天,用js梳理了一下数据结构。

那么这个夏天,一起用C语言来品味一下数据结构之美吧。

下面这段程序就是单链表的建立函数。

里面的细节主要在于创建链表中的节点node,然后用指针将这些节点进行衔接。

需要注意的是,头节点的初始化:

head=(node*)malloc(sizeof(node));

节点指针的移动:

p->next=s;
p=s;

以及对于边界条件的处理:

head = head->next;
p->next = NULL;

整体程序如下:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>
using namespace std;

typedef struct student
{
int data;
struct student *next;
}node;

node *creat()
{
node *head,*p,*s;
int x,cycle=1;
head=(node*)malloc(sizeof(node));
p=head;
while(cycle)
{
cout<<"\n please input the data: ";
cin>>x;
if(x!=0)
{
s=(node *)malloc(sizeof(node));
s->data = x;
cout<<"\n"<<s->data;
p->next=s; p=s;
}
else
{
cycle=0;
}

}
head = head->next; p->next = NULL;
cout<<head->data;
return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  单链表