链表c的经典实现(一)
2023-09-14 09:15:52 时间
//本书代码来思想自于创客诚品的<<C语言从入门到精通>>
//但我对原书代码做了较大的改动;
// 个人认为算法与数据结构是一个程序员的内功,欲成为第一流的高手必须苦练内功
// 欲研究数据结构,必须写C
#include<stdio.h>
#include<stdlib.h>
#define N 10
//定义一个结构体,这里有一点难以理解,next 采用了嵌套定义
// struct list
typedef struct list
{
int data;
struct list *next;
}SLIST;
main()
{
SLIST *head ,*p,*q;
int x;
//这是链表的第一个节点
head=p=(SLIST *)malloc(sizeof(SLIST));
scanf("%d",&x);
while(x>0)
{
q=(SLIST *)malloc(sizeof(SLIST));
q->data=x;
p->next=q;
p=q;
scanf("%d",&x);
//q=(SLIST *)malloc(sizeof(SLIST));
}
//p=head->next; //下面为打印一个链表
p=head->next; //下面为打印一个链表
while(p!=NULL)
{
printf("%d\n",p->data);//输出当前节点的数据
q=p; //删除当前节点
p=p->next;
free(q); //释放删除的
}
return ;
}
luogan@luogan-Lenovo-G470:~/lg/temp/实用数据结构$ ./a.out
1
2
3
-9
1
2
3