单链表的插入和删除
1 单链表插入
要想将结点s插入到ai与ai+1之间,不需要移动数据元素,只需要在ai与ai+1之间插入一个新的结点,也就是我们要插入的结点s。关键就是要修改结点p的指针域,使得结点s称为其后继。
修改指针的链接的主要操作语句是:
1. s->next=p->next; //把结点p的后继作为结点s的后继;
2. p->next=s; //把结点s作为结点p的后继;
注意这两个语句的顺序不能调换不能调换不能调换!!!
为什么呢?如果调换①和②的顺序,那么插入操作就无法完成,并且会丢失ai结点的地址以及ai及其后面所有结点的信息。
2 单链表删除
删除操作和插入类似,在删除一个结点时,不需要移动元素,仅需要修改相应的指针链接,改变其前驱和后继的关系即可。
主要操作语句为(要借助辅助指针变量q):
1. q = p->next; //首先保存b的指针,靠它才能找到c;
2. p->next=q->next; //将a、c两结点相连,淘汰b结点;
3. free(q); //释放被删除结点的空间
3 代码实现
以下代码实现了 单链表的按位置插入和删除
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElementType;
typedef struct node {
ElementType data;
struct node *Next;
} *List;
List CreateList(void)
{
List L = (List)malloc(sizeof(struct node));
L->data = 0;
L->Next = NULL;
return L;
}
void InitList(List L)
{
srand((unsigned)time(NULL));
for (int i = 0; i < 10; i++) {
List p = (List)malloc(sizeof(struct node));
p->data = rand() % 100;
p->Next = L->Next;
L->Next = p;
}
}
List Find(List L, int position)
{
List p = L;
int i = 0;
while (p->Next && i < position) {
p = p->Next;
i++;
}
if (i == position) {
return p;
} else {
return NULL;
}
}
void Insert(List L, int position, ElementType e)
{
List p;
List tmp;
if (p = Find(L, position - 1)) {
tmp = (List)malloc(sizeof(struct node));
tmp->data = e;
tmp->Next = p->Next;;
p->Next = tmp;
}
}
void Delete(List L, int position)
{
List p;
List tmp;
if (p = Find(L, position - 1)) {
tmp = p->Next;
p->Next = tmp->Next;
free(tmp);
}
}
void PrtList(List L)
{
List p = L->Next;
while (p) {
printf("%d ", p->data);
p = p->Next;
}
printf("\n");
}
int main(void)
{
ElementType e;
int position;
List L = CreateList();
InitList(L);
PrtList(L);
printf("please input position and element to insert:");
scanf("%d%d", &position, &e);
Insert(L, position, e);
PrtList(L);
printf("please input position to delete:");
scanf("%d", &position);
Delete(L, position);
PrtList(L);
return 0;
}
运行结果如下图: