#include<iostream>
#define ElemType int
using namespace std;
typedef struct Node {
ElemType data;
struct Node *next;
};
void Create(Node *&l) { //尾插法
int x;
l->next = NULL; //头结点
Node *s,*r = l; //r为表尾指针
cin >> x;
while (x != -1) {
s = new Node;
s->data = x;
r->next = s;
r = s;
cin >> x;
}
r->next = NULL;
}
void Print(Node *&l) { //输出链表中的数据
Node *p = l->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void Delete(Node *&l) { //单链表的删除操作
Node *p = l;
Node *q = l->next; //保存后继指针,防止断链
while (p!= NULL ) {
delete p;
p = q;
if (q != NULL) {
q = q->next;
}
}
}
void Unique(Node *&l) {
Node *pre = l->next; //保存当前结点的前驱
Node *p = pre->next, *r = NULL;
while (pre != NULL && p!=NULL) { //判断是否结束
if (pre->data == p->data) { //相等则删除
r = p->next; //保存后继指针
pre->next = p->next;
delete p;
p = r;
}
else {
pre = p; //进行下一次的循环
p = p->next;
}
}
}
int main() {
Node *l = new Node; //新建结点,并且创建指针
Create(l);
Print(l);
Unique(l);
Print(l);
Delete(l); //释放内存
system("pause");
return 0;
}
/*
7 10 10 21 30 42 42 42 51 70 -1
*/