编码实现环状单项链表(尾指针直接指向头指针,之间没有空节点),去掉连续的重复元素的操作。
#include<iostream>
#include<vector>
using namespace std;
struct Tnode{
int value;
Tnode* next;
Tnode(int x) :value(x), next(NULL){}
};
Tnode* unique(Tnode* head){
if (head == NULL || head->next == NULL){
return head;
}
Tnode* pre = head;
Tnode* p = head->next;
while (p != head){
if (pre->value == p->value){
Tnode* tmp = p;
pre->next = p->next;
p = p->next;
delete tmp;
}
else{
pre = p;
p = p->next;
}
}
//处理头尾相同的情况
if (pre->value == p->value){
pre->next = p->next;
delete p;
return pre;
}
return head;
}
Tnode* creatLink(vector<int> a){
Tnode* head = new Tnode(a[0]);
Tnode* p = head;
for (int i = 1; i < a.size(); i++){
Tnode* u = new Tnode(a[i]);
p->next = u;
p = u;
}
p->next = head;
return head;
}
int main(){
vector<int> a = { 1, 2, 2, 3, 3, 1 };
Tnode* head = creatLink(a);
head= unique(head);
Tnode* p = head;
while (p->next != head){
cout << p->value << " ";
p = p->next;
}
cout << p->value;
cout << endl;
return 0;
}