1.插在链表开头
新的节点插入到链表的开头,需要将新节点的指针指向链表的首节点,并将链表的首节点设为新节点。
New->next = Pointer;
Head = New;
2.插在链表中间
新的节点插入到链表的中间,如果我们找到Pointer节点,则需要将新节点的指针指向Pointer节点的指针(即下一个节点),但不能让链表断裂。所以第一步必须将新节点的指针指向Pointer节点的指针,第二步再讲Pointer节点的指针指向新节点。
New->next = Pointer->next;
Pointer->next = New;
3,插在链表尾端
新的节点插入到链表的尾端(Pointer节点),所以第一步必须将新节点的指针指向Pointer节点的指针(NULL),第二步再将Pointer节点的指针指向新节点
New->next = Pointer->next;
Pointer->next = New;
示例:设计一个链表内节点插入的程序。
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct List
{
int number;
int total;
struct List *next;
};
typedef struct List Node;
typedef Node *Link;
int data[2][MAX] = {1, 3, 5, 7, 2, 4, 6, 8, 9, 0, 15, 35, 20, 23, 33, 45, 55, 56, 15, 10};
/**********************
* 插入节点至链表内
**********************/
Link insert_list(Link head, Link new, int key)
{
Link pointer;
pointer = head;
while(1)
{
if(pointer == NULL) //插在首节点
{
new->next = head;
head = new;
break;
}
if(pointer->number == key) //插在链表中间或尾端
{
new->next = pointer->next;
pointer->next = new;
break;
}
pointer = pointer->next; //往下一个节点
}
return head;
}
/**********************
* 释放链表
*********************/
Link free_list(Link head)
{
Link pointer;
while(head != NULL)
{
pointer = head;
head = head->next;
free(pointer);
}
}
/**********************
* 输出链表
*********************/
Link print_list(Link head)
{
Link pointer; //节点声明
pointer = head; //pointer指针设为首节点
while(pointer != NULL)
{
printf("[%d, %d]", pointer->number, pointer->total);
pointer = pointer->next;
}
printf("\n");
}
/**********************
* 建立链表
*********************/
Link create_list(Link head)
{
Link new; //节点声明
Link pointer;
int i;
head = (Link)malloc(sizeof(Node)); //分配内存
if(head == NULL)
{
printf("Memory allocate failure!\n");
}
else
{
head->number = data[0][0]; //定义首节点
head->total = data[1][0];
head->next = NULL;
pointer = head; //将pointer指针设为首节点
for(i = 1; i < MAX; ++i)
{
new = (Link)malloc(sizeof(Node));
new->number = data[0][i];
new->total = data[1][i];
new->next = NULL;
pointer->next = new; //将新节点串联在原列表尾端
pointer = new; //列表尾端节点为新节点
}
}
return head;
}
int main()
{
Link head; //节点声明
Link new;
int key = 0;
head = create_list(head); //建立链表
if(head != NULL)
{
print_list(head);
while(1)
{
printf("Input 0 to exit!\n");
new = (Link)malloc(sizeof(Node)); //分配内存
printf("Please input the data number: ");
scanf("%d", &new->number);
if(new->number == 0) //输入0时结束
break;
printf("please input the data total: ");
scanf("%d", &new->total);
printf("Please input the data number for insert: ");
scanf("%d", &key);
head = insert_list(head, new, key); //调用插入节点接口
print_list(head); //打印链表
}
free_list(head); //释放链表
}
return 0;
}