最近在学数据结构,以前学校学的太水了,自己重新看一遍吧,先从最简单的开始吧,来个单向链表的创建与打印
<pre name="code" class="cpp">#include<stdio.h>
#include<malloc.h>
struct node
{
int data; //elementype表示一种数据类型,可能是int/char等等
struct node *next; //next 指针,用于链表结构指向下一个节点
};
typedef struct node node; //重定义struct node类型为node
void List(node* head);
node* Creat();
int main()
{
node* head;
head = Creat();
List(head);
return 0;
}
int n;
node* Creat()
{
node *p1,*p2,*head;
n = 0;
p1 = p2 = (node*)malloc(sizeof(node));
scanf("%d",&p1->data);
head = NULL;
while(p1->data!=0)
{
n = n+1;
if(n == 1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (node*)malloc(sizeof(node));
scanf("%d",&p1->data);
}
p2->next = NULL;
return(head);
}
void List(node* head)
{
node *p1;
p1 = head;
while(p1!= NULL)
{
printf("%d\n",p1->data);
p1 = p1->next;
}
}
运行结果: