带头结点的单链表L,删除所有值为x的结点,并释放空间,假设x唯一 -002

带头结点的单链表L,删除所有值为x的结点,并释放空间,假设x唯一

总结

删除结点时,使用first,second两个指针来遍历删除

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;

LinkList Del_X(LinkList &L,int x){
LNode *first,*second; //first,second两个指针一前一后,遍历整个链表,并实现删除时连接
second=L;
first=L->next;
while(first!=NULL){
if(first->data==x){
second->next=first->next;
delete first;
first=second->next;
}else{
first=first->next;
second=second->next;
}
}
return L;
}

评论