PAT-1097(Depulication on a Linked List)
题目见这里
分析:实际上是静态链表的应用,只不过要删除的结点链接成一个新的Removed List
//静态链表 #include <stdio.h> #define KEYMAX 10005 #define MAXADDRESS 100005 typedef struct{ int data; int next; //下一个元素的下标 }SLinkList; int n,kHead,rHead; SLinkList sLinkList[MAXADDRESS]; int flag[KEYMAX]; int Transform(char *address){ if(address[0]=='-') return -1;//仅-1为负数 int p,i; p=0,i=0; while(address[i]){ p = 10*p+address[i]-'0'; i ++; } return p; } void Read(){ char address[6],next[6]; int data,p; scanf("%s%d",address,&n); getchar(); kHead = Transform(address); while(n--){ scanf("%s%d%s",address,&data,next); p = Transform(address); sLinkList[p].data = data; sLinkList[p].next = Transform(next); } } void DeDuplication(){ int prior,next,q,data,i=1; prior = next = kHead; while(next!=-1){ data = sLinkList[next].data; if(data<0) data = -data; if(flag[data]){ //删除结点 sLinkList[prior].next = sLinkList[next].next; if(i==1){ rHead = next; q = rHead; sLinkList[q].next = -1; i ++; } else{ sLinkList[q].next = next; sLinkList[next].next = -1; q = next; } //next结点链接到rHead所在链表之后再更新next next = sLinkList[prior].next; } else{ flag[data] = 1; prior = next; next = sLinkList[next].next; } } } void OutPut(int head){ int p = head; if(p==-1) return; //removed list可能为空 do{ printf("%05d %d ",p,sLinkList[p].data); if(sLinkList[p].next!=-1) printf("%05d\n",sLinkList[p].next); else printf("-1\n"); p = sLinkList[p].next; }while(p!=-1); } int main(){ // freopen("Data.txt","r",stdin); kHead = rHead = -1; Read(); // OutPut(kHead); // puts("~~~分界线~~~"); DeDuplication(); OutPut(kHead); OutPut(rHead); return 0; }