2016-04-06 31 views
1

我有一個列表:
1-2-3-3-4-5-6-6-2-7-8-6-9-10-9-NULL // Before
我Wnt信號,使其如下:
1-2-3-4-5-6-7-8-9-10空//後
我已經寫了下面的代碼:

刪除鏈接列表中的重複元素

void don(struct node *head) 
{ 
struct node *t,*p,*q; 
t=head; 
p=t->next;//p is to check each node! 
q=t;//q is used to take care of previous node! 
while(p!=NULL) 
{ 
    if(p->data==t->data) 
    { 
     while(p->data==t->data) 
     { 
      p=p->next; 
     } 
     q->next=p; 
     q=q->next; 

    } 
    else 
    { 
     p=p->next; 
     q=q->next; 
    } 
} 
t=t->next; 
if(t!=NULL) 
    don(t); 
} 

但輸出是:
1-2-3-4-5-6-7-8-6-9-10
請告訴我代碼中出現了什麼問題,請更正它:)。

+0

一件事錯的是你正在泄漏內存。 –

+0

它看起來像你只是檢查相鄰的重複。 – interjay

+0

你只是跳過連續的錯誤 – CarlH

回答

1

試試下面的函數(未經測試)

void don(struct node *head) 
{ 
    for (struct node *first = head; first != NULL; first = first->next) 
    { 
     for (struct node *current = first; current->next != NULL;) 
     { 
      if (current->next->data == first->data) 
      { 
       struct node *tmp = current->next; 
       current->next = current->next->next; 
       free(tmp); 
      } 
      else 
      { 
       current = current->next; 
      } 
     } 
    } 
} 

至於你的函數,則函數的甚至一開始就是錯誤的

void don(struct node *head) 
{ 
struct node *t,*p,*q; 
t=head; 
p=t->next;//p is to check each node! 
//... 

一般head可以等於NULL在t他的案例p=t->next;這一陳述導致未定義的行爲。

編輯:如果函數必須是遞歸的話,就看看下面的方式

void don(struct node *head) 
{ 
    if (head) 
    { 
     for (struct node *current = head; current->next != NULL;) 
     { 
      if (current->next->data == head->data) 
      { 
       struct node *tmp = current->next; 
       current->next = current->next->next; 
       free(tmp); 
      } 
      else 
      { 
       current = current->next; 
      } 
     } 

     don(head->next); 
    } 
} 
0

你應該有一個嵌套的同時:

p= head; 
while(p) 
{ 
    q=p->next; 
    while(q) 
    { 
     if (p->data==q->data) 
      ... //remove 
     q= q->next; 
    } 
    p= p->next; 
}