C语言里面链表是一种常用的数据结构,创建链表的方式有很多,其中使用压栈的方式比较方便,本文使用指针实现直接在一个已有的链表头部插入一个新的结点。
比如已经存在链表struct node *BuildList(),链表中有两个结点0,1,head指向0,然后在0的前面添加4个结点,结点中的数据分别是2,3,4,5。
代码如下:
#include <stdlib.h>#include <stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *BuildList() //函数创建一个只有数字0和1两个结点的链表
{
struct node *head = malloc(sizeof(struct node));
struct node *one = malloc(sizeof(struct node));
head->data = 0;
head->next = one;
one->data = 1;
one->next = NULL;
}
void push_node(struct node **newhead, int data) //传递的是链表的当前结点的地址,这样可以直接修改链表中的值
{
struct node *addednode=malloc(sizeof(newhead));
addednode->data = data;
addednode->next = *newhead;
*newhead = addednode;
}
void pop_node(struct node **currnode) //打印从传入的地址为起始地址的一个链表
{
struct node *curr=malloc(sizeof(currnode));
curr = *currnode;
while(curr != NULL)
{
printf("%d\n", curr->data);
curr = curr->next;
}
}
main()
{
struct node *newlist=BuildList();
struct node *backhead = malloc(sizeof(struct node));
backhead->next = newlist;
int i;
for(i=2; i<6; i++)
{
push_node(&backhead, i);
printf("%d\n", backhead->data);
}
printf("The linked list is:\n");
pop_node(&backhead);
}
说明:push_node添加一个结点,类似于堆栈的压栈操作,先压入的在链表靠后的位置,所以pop_node弹出的时候打印的是最后添加的结点。
运行结果如下:
[xxxx@xxxxx C]$ ./add_node
2
3
4
5
The linked list is:
5
4
3
2
0
1