注意:不带头节点的单链表删除插入操作第一个节点的时候都要特殊讨论
以下代码是用C语言实现的完整代码可上机运行
#include<stdio.h>
#include<malloc.h>
struct linknode
{
int data;
struct linknode* next;
};
void init(struct linknode** L)
{
(*L) = NULL;
}
void insect(struct linknode** L, int i, int n)
{
if (i < 1)
printf("插入位置错误\n");
else if (i == 1)
{
printf("开始插入\n");
struct linknode* s = (struct linknode*)malloc(sizeof(struct linknode));
printf("申请位置成功\n");
s->data = n;
s->next = (*L);
(*L) = s;
printf("插入成功\n");
}
else
{
int count = 1;
struct linknode* p = (*L);
while (p&&count < i - 1)
{
p = p->next;
count++;
}
if (p)
{
struct linknode* s = (struct linknode*)malloc(sizeof(struct linknode));
s->data = n;
s->next = p->next;
p->next = s;
printf("插入成功\n");
}
else
printf("插入失败\n");
}
}
void delete(struct linknode** L,int i)
{
if(i<1||(*L)==NULL)
printf("删除失败");
else if(i==1)
{
(*L)=(*L)->next;
}
else
{
int count=1;
struct linknode* p=(*L);
while(p&&count<i-1)
{
p=p->next;
count++;
}
if(p)
{
p->next=p->next->next;
printf("删除成功\n");
}
else
printf("删除位置不恰当\n");
}
}
void point(struct linknode* L)
{
while (L)
{
printf("%d,", L->data);
L = L->next;
}
}
int main()
{
struct linknode* L;
init(&L);
printf("初始化成功不带头节点单链表\n");
insect(&L, 1, 11);//在第一个位置插入元素11
insect(&L, 2, 22);
insect(&L, 3, 33);
insect(&L, 3, 44);
insect(&L, 6, 66);
delete(&L,1);//删除第一个元素
delete(&L,3);//删除第三个元素
delete(&L,5);//删除第五个元素
printf("请打印输出链表\n");
point(L);//打印函数
return 0;
}
运行结果: