首页 > 代码库 > [002] delete_duplication_of_linked_list
[002] delete_duplication_of_linked_list
[Description] Given a unsort linked list, delete all the duplication from them, no temporary space permission.
[Thought] Set two points, from head to tail, scaning all linked list. O(n^2).
[Implementation] C code:
1 #include<stdio.h> 2 3 typedef struct linkedList 4 { 5 int data; 6 struct linkedList* next; 7 } llist; 8 9 llist** delDupli(llist **head)10 {11 // two point, t1 for target, t2 for mover.12 llist *t1, *t2;13 t1=t2=*head;14 while(t1->next != NULL)15 {16 // ajust t2 from t1!17 t2=t1;18 while(t2->next != NULL)19 {20 // check if they are the same21 if(t2->next->data =http://www.mamicode.com/= t1->data)22 {23 // move t2->next; note: no memory free here.24 t2->next=t2->next->next;25 }26 // after move out node, check if t2 is already the last one.27 if(t2->next != NULL)28 {29 t2=t2->next;30 }31 }32 t1=t1->next;33 }34 return head;35 }36 37 int addValue(llist **head, int val)38 {39 40 llist *pnode;41 llist *t=*head;42 // apply memory for linked list.43 pnode=(llist*)malloc(sizeof(llist));44 if(NULL==pnode)45 {46 return 0;47 }48 pnode->data=http://www.mamicode.com/val;49 pnode->next=NULL;50 // first node51 if(NULL==*head)52 {53 *head=pnode;54 return 1;55 }56 // move temp point to the last node57 while(t->next != NULL)58 {59 t=t->next;60 }61 t->next=pnode;62 return 1;63 }64 65 // out put data, be careful about the first node.66 int printList(llist **head)67 {68 llist *t=*head;69 printf("%d, ",t->data);70 while(t->next != NULL)71 {72 t=t->next;73 printf("%d, ",t->data);74 }75 printf("\n");76 return 1;77 }78 79 int main()80 {81 int a[]={2,3,5,6,8,2,4,6,8,9,2,5,2};82 llist *head=NULL;83 int i;84 85 for(i=0;i<(sizeof(a)/sizeof(a[0]));i++)86 {87 // printf("a[i]:%d\n",a[i]);88 addValue(&head,a[i]);89 // printList(&head);90 }91 printf("Initial linked list:\n");92 printList(&head);93 printf("After deleting:\n");94 printList(delDupli(&head));95 }
[002] delete_duplication_of_linked_list
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。