首页 > 代码库 > 单链表的删除
单链表的删除
将表的第i个节点删去:
- 找到ai-1存储位置p
- 保存要删除的结点的值
- 另p->next指向ai的直接后继结点
- 释放结点的空间
如图:
代码:
include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
//建立一个只含头结点空链表
int InitList_L(LinkList &L){
L=(LinkList)malloc(sizeof(LNode));
if(!L){
exit(OVERFLOW); // 存储分配失败
}
L->next=NULL;
return OK;
}
//建立含n个元素的单链表,并且是尾插入,
int CreateList_L(LinkList &L,int n){
LinkList p,q;
int i;
printf("Input the datas:");
q=L;
for(i=0;i<n;i++){
p=(LinkList)malloc(sizeof(LNode));
scanf("%d",&p->data);
p->next=q->next;
q->next=p;
q=p;
}
return OK;
}
//若表中存在第i个结点删除并用e带回其值
int ListDelete_L(LinkList &L,int i,int &e){
LinkList p,q;
int j=0;
p=L;
while(p->next&&j<i-1){//查找第i个结点,若存在,p指向其直接前驱
p=p->next;
++j;
}
while(!(p->next)||j>i-1){
return ERROR;
}
q=p->next;//q指向第i个结点
p->next=q->next;
e=q->data;
free(q);
return OK;
}
main(){
int i,n,e;
LinkList L;
InitList_L(L);
printf("Input the length of the list L:");
scanf("%d",&n);
CreateList_L(L,n);
printf("Input the delete location:");
scanf("%d",&i);
if(ListDelete_L(L,i,e)){
printf("Output the datas:");
TraverseList_L(L);
}else{
printf("Can‘t find the delete data!\n");
}
printf("\n");
}
结果:
android@android-Latitude-E4300:~/work/c/danlianbiao$ ./listDelete
Input the length of the list L:5
Input the datas:1 3 5 7 9
Input the delete location:3
Output the datas:1379
单链表的删除