描述:
给一个排好序的链表,如 1->2->3->3->5; 删除其中的重复元素之后结果为 1->2->5
思路:
遍历链表,用pre指针记录当前节点的前一个节点,然后每次遍历的时候比较 p->data 与 p->next->data。其中需要注意的是,需要一个标记,来处理pre是直接后移,还是需要再跳过重复元素。
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node(int x):data(x),next(nullptr){}
};
Node* deletSameElement(Node* List) {
Node* p = List;
Node* pre = p;
Node* res = List;
p = p->next;
bool flag = 0;
while(p != nullptr) {
if (p->next != nullptr) {
if (p->data == p->next->data) {
p = p->next;
flag = 1;
}
else {
if (flag == 0) {
pre = p;
p = p->next;
}
else {
pre->next = p->next;
p = p->next;
flag = 0;
}
}
}
else break;
}
return res;
}
void build() {
Node* List = new Node(0);
Node* tmp = new Node(1);
List->next = tmp;
Node* tmp2 = new Node(2);
tmp->next = tmp2;
Node* tmp3 = new Node(3);
tmp2->next = tmp3;
Node* tmp4 = new Node(3);
tmp3->next = tmp4;
Node* tmp5 = new Node(5);
tmp4->next = tmp5;
Node* p = List;
while(p != nullptr) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
Node* res = deletSameElement(List);
while(res != nullptr) {
cout << res->data <<" ";
res = res->next;
}
}
int main() {
build();
return 0;
}