
程序代码:
#include<stdio.h>
#include<stdlib.h>
//类型声明
//节点数据
typedef int ElemType;
//节点
typedef struct Node{
ElemType data;
struct Node *next;
}Node;
//链表
typedef struct List{
int size;
Node header;
Node tailer;
}List;
int main(void){
List l,*lp1,;
lp1=_ListInit();
lp1=ListInsertData(lp1,20);
lp1=ListInsertData(lp1,20);
lp1=ListInsertData(lp1,20);
lp1=ListInsertData(lp1,40);
lp1=ListInsertData(lp1,40);
printf("\n---------\nlp1:\n");
ListPrint(lp1);
lp1=ListDeduplicate(lp1);
printf("\n---------\nlp1:\n");
ListPrint(lp1);
return 0;
}
//链表建立
List *_ListInit(void){
List *L;
L=(List *)malloc(sizeof(List));
L->header.next=&(L->tailer);
L->tailer.next=NULL;
L->size=0;
L->header.data=0;
L->tailer.data=0;
printf("List create successfully!\n");
return L;
}
//链表插入,接受数据
//作为头指针的下一个节点插入
List *ListInsertData(List *L,ElemType Data){
if (!L)printf("Error!");
Node N;
N.next=L->header.next;//将原首元素接到临时指针上
L->header.next=(Node *)malloc(sizeof(Node));//头元素的指针域生成新节点
L->header.next->data=Data;//赋值
L->header.next->next=N.next;//原来的节点接到新增节点后
L->size++;
return L;
}
//链表唯一化
List *ListDeduplicate(List *L){
Node *temp,*N=L->header.next; //从首元素开始
ElemType Data; int i=1;
while(NULL!=N->next){//到达尾节点
N=L->header.next;
Data=N->data;
while(NULL!=N->next){
N=N->next;
if(N->data==Data){
printf("%d\n",i);i++;
temp=N->next->next;
N->next=temp;
free(temp);
L->size--;
}
}
}
return L;
}
//遍历打印
void ListPrint(List *L){
if(!L)printf("Error!");
if(L->size==0)printf("Empty List!\n");
Node *N=L->header.next;//临时指针指向首元素
int i=1;
printf("List length:%d\n",L->size);
while(NULL!=N->next){
printf("number:%d\tdata:%d\n",i,N->data);
N=N->next;
i++;
}
printf("---------\n");
}