链表表示删除重复元素
Write code to remove duplicates from an unsorted linked list
FOLLOW UP
线性表的定义;
构造线性表,并遍历(打印线性表);
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
如果我们用缓冲区,我们可以在hash表里跟踪每一个元素,同时删除任何重复的。
本文主要是记载线性表的一些实现方法。
struct LNode { ElemType data; struct LNode *next; }; typedef struct LNode *Linklist;
线性表的定义;
void CreatList(Linklist *L,int n)//创建线性链表 { int i; Linklist p; *L=(Linklist)malloc(sizeof(struct LNode)); (*L)->next=NULL; printf("请输入%d个数据\n",n); for(i=n;i>0;i--) { p=(Linklist)malloc(sizeof(struct LNode)); scanf("%c",&p->data); p->next=(*L)->next; (*L)->next=p; } } int ListTraverse(Linklist L,void(*vi)(ElemType)) { Linklist p=L->next; while(p) { vi(p->data); p=p->next; } printf("\n"); return 1; } void print(ElemType a) { printf("%c ",a); }
构造线性表,并遍历(打印线性表);
void delDuplicates(Linklist L) { bool hit[MAX]={false}; int tmp; ElemType e; Linklist p=NULL; p=(Linklist)malloc(sizeof(struct LNode)); while(L!=NULL) { e=L->data; if(hit[e-'0']) p->next=L->next; else { hit[e-'0']=true; p=L; } L=L->next; } }
上面是申请了额外的缓冲区,下面是没有申请额外空间时的算法、
当没有缓冲区的时候,我们可以循环两个指针,current是正常的循环,runner循环current之前的所有节点,从而判断是否重复。
void delDuplicates1(Linklist L) { if(L==NULL) return; Linklist previous=L; Linklist current=previous->next; while(current!=NULL) { Linklist runner=L; while(runner!=current) { if(runner->data==current->data) { Linklist tmp=current->next; previous->next=tmp; current=tmp; break; } runner=runner->next; } if(runner==current) { previous=current; current=current->next; } } }