数据结构_无头结点链表的插入定位和删除操作
不带头结点的单链表各种操作(定位,插入,删除)的实现,从中可以明白单链表带头结点的优势,可以保证循环代码的一致性,而无需分支判断。
include<stdio.h>
include<stdlib.h>
//定义结构体类型
typedef struct linktable {
float m;
struct linktable * Next;
}node;
//打印单链表
void showprint(node *L) {
while (L != NULL) {
printf("%f->", L->m);
L = L->Next;
}
}
//单链表定位
int loction(node* L,float datas) {
int count = 0;
while (L->m != datas)
{ L = L->Next;
count++;
}//of while
return count;
}
//向单链表插入数据
void Insert(node* L, float datas,int index){
node * new= (node *)malloc(sizeof(node));
new->m = datas;
new->Next = NULL;
int count = 0;
if (index == 0) {
new->Next = L;
showprint(new);
}
else
{
while (count != index - 1) {
L = L->Next;
count++;
}
new->Next = L->Next;
L->Next = new;
}
}
//删除单链表数据
node* DeleteData(node * L, int index) {
int count = 0;
if (index == 0) {
node * r = L;
L = L->Next;
free(r);
}else{
node *top = L;
while (count != index-1) {
top = top->Next;
}
node *p = top->Next;
node *q = p->Next;
p->Next = NULL;
top->Next = q;
free(p);
}
return L;
}
void main() {
node * node1 = (node )malloc(3sizeof(node));
node1->Next=(node *)malloc(1 * sizeof(node));
node1->Next->Next = (node *)malloc(1 * sizeof(node));
node1->m = 2.1;
node1->Next->m = 3.1;
node1->Next->Next->m = 5.1;
node1->Next->Next->Next = NULL;
int a = loction(node1, 3.1);
printf("count=%d",a);
printf("\n");
showprint(node1);
printf("\n");
Insert(node1, 6.8, 0);
//showprint(node1);
printf("\n");
Insert(node1, 8.8, 1);
showprint(node1);
printf("\n");
node * b=DeleteData(node1, 0);
showprint(b);
printf("\n");
node * c = DeleteData(b, 1);
showprint(c);
printf("\n");
}
----------------------------------操作运行结果-------------------------------

上文代码中的插入模块有点点小问题,你们看出来了吗?欢迎大家留言自己的观点。
