编写算法删除单链表中"多余"的数据元素,即使操作之后的单链表中所有元素的值都不相同。
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define TRUE 1;
#define FALSE 0;
#define OK 1;
#define ERROR 0;
#define INFEASIBLE - 1;
typedef int Status;
typedef int ElemType;
typedef struct LList {
ElemType elem;
struct LList* next;
}LList;
LList InitList_L(int size) {
LList* head = NULL;
LList* p = (LList*)malloc(sizeof(LList));
head = p;
p->elem = 0;
p->next = NULL;
for (int i = 0; i < size; i++) {
LList* temp = (LList*)malloc(sizeof(LList));
p->next = temp;
p = temp;
p->elem = i/2;
p->next = NULL;
}
return *head;
}
Status GetElem_L(LList& L, int loc, ElemType& e) {
int i;
LList* temp = &L;
for (i = 1; i < loc; i++) {
temp = temp->next;
}
e = temp->elem;
return OK;
}
LList ListDelete_L(LList& L, int loc, ElemType& e) {
int i;
LList* temp = &L;
LList* head = &L;
if (loc == 1) {
head = L.next;
free(temp);
return *head;
}
for (i = 1; i < loc - 1; i++) {
temp = temp->next;
}
LList* p = temp->next;
temp->next = p->next;
e = p->elem;
free(p);
return *head;
}
LList InsertElem_L(LList& L, int loc, ElemType e) {
int i;
LList* temp = &L;
LList* head = &L;
LList* p = (LList*)malloc(sizeof(LList));
p->elem = e;
if (loc == 1) {
head = p;
p->next = temp;
return *head;
}
for (i = 1; i < loc - 2; i++) {
temp = temp->next;
}
p->next = temp->next;
temp->next = p;
return *head;
}
Status Print_L(LList& L) {
LList* temp = &L;
cout << "out the table:";
while (!(temp->next == NULL)) {
cout << temp->elem << ' ';
temp = temp->next;
}
cout<< temp->elem << ' ' << endl;
return OK;
}
Status DelRepeatList(LList& L) {
LList* temp = &L;
while (temp->next != NULL) {
LList* temp1 = temp;
while (temp1->next != NULL) {
temp1 = temp1->next;
if (temp->elem == temp1->elem) {
LList* p = temp1;
temp1 = temp;
while (temp1->next != p) {
temp1 = temp1->next;
}
temp1->next = p->next;
free(p);
}
}
if (temp->next == NULL) {
break;
}
temp = temp->next;
}
return OK;
}
int main() {
LList A;
A.elem = 0;
A.next = NULL;
A = InitList_L(10);
cout << "first table\n";
Print_L(A);
DelRepeatList(A);
cout << "\n after delete";
Print_L(A);
return 0;
}