每日一題之刪除排序連結串列重複元素
阿新 • • 發佈:2018-11-19
描述:
給一個排好序的連結串列,如 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;
}