链表

1
2
3
4
struct node{
int data;
struct node *next;
}

链表的构建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//例子:读入一个数字n,再连续读入n个数字,将这些数字组成链表
void build_node(int n)
{
int i,temp;
struct node *head,*p,*q;
for(i=1;i<=n;i++){
scanf("%d",&temp);
p=(struct node *)malloc(sizeof(struct node)); //开辟一个堆空间中的struct node大小的存储空间
p->data=temp; //将读入的数字存入这个存储空间中
p->next=NULL; //新建链表时,每读入一个元素都是表尾
if(head==NULL) //
head=p;
else
q->next=p;
q=p; //将当前创建的
}
}

链表的访问

1
2
3
4
5
6
7
8
void request(struct node *head)
{
struct node *t=head;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
}

链表的插入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//假设链表中的数据是从小到大排列好的,现在要向其中插入一个数字a,使其仍然维持升序排列
void insert(int a,struct node *head)
{
struct node *t=head;
while(t!=NULL){
if(t->next!=NULL||t->next->data>a){
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next=t->next;
t->next=p;
break;
}
t=t->next;
}
}