2013-05-04 141 views
3

我正在嘗試C程序從排序鏈接列表中刪除重複項,我正在使用遍歷列表從開始節點的簡單概念。遍歷時,將每個節點與下一個節點進行比較。如果下一個節點的數據與當前節點相同,那麼我刪除下一個節點。從排序的鏈接列表中刪除重複的元素

我的代碼是:

struct node *remove_dup(struct node *start) 
{ 
    struct node *p,*tmp; 
    p=start; 
    while(p!=NULL) 
    { 
     if(p->info==p->link->info) 
     { 
      tmp=p->link; 
      p->link=p->link->link; 
      free(tmp); 
     } 
     p=p->link; 
    } 
    return start; 
} 

它不給我正確的答案!我的執行有什麼問題?我的觀念錯了嗎?

+1

什麼是不會產生正確結果的輸入示例? – Xymostech 2013-05-04 13:55:50

+4

'p = p-> link;'語句需要進入'else'分支。 – 2013-05-04 13:56:05

+0

你有什麼錯誤嗎? – 2013-05-04 13:56:12

回答

4

因爲你的代碼檢查下一個元素,你需要停下來,當你在元素一個前的最後,是這樣的:

while (p != NULL && p->link != NULL) { 
    ... 
} 

的唯一原因具備條件的第一部分是陷阱空的列表。

另外,當你移除一個元素時,你不應該前進指針。否則,您將不會正確處理超過兩個元素的運行。

+0

Thanku!有效! – poorvankBhatia 2013-05-04 13:59:00

2
struct node *remove_dup(struct node *start) 
{ 
    struct node *p,*next; 

    for(p=start; p; p = next) { 
     next = p->link; 
     if(!next || p->info != next->info) continue; 
     p->link = next->link; 
     free(next); 
     next = p; 
    } 
    return start; 
} 

或同等學歷(不搞亂下一個)

struct node *remove_dup(struct node *start) 
{ 
    struct node *p; 

    for(p=start; p;) { 
     struct node *next = p->link; 
     if(!next || p->info != next->info) { p = next; continue; } 
     p->link = next->link; 
     free(next); 
    } 
    return start; 
} 
+0

在for循環中使用'p = p-> link'不是更好嗎? (我的意思是內部---- for(;; p = p-> link)) – Bill 2013-05-04 15:07:37

+0

不,因爲你不想在刪除之後前進。 – wildplasser 2013-05-04 15:09:02

+0

但這正是你在循環的第一行所做的? – Bill 2013-05-04 15:10:37

0

我的答案在Java中:

public void removeDuplicate() { 
    if (first == null) { 
     throw new NoSuchElementException("The linkedlist contains no nodes."); 
    } 
    Node temp = first; 
    while (temp != null && temp.next != null) { 
     if (temp.element == temp.next.element) { 
      temp.next = temp.next.next; 
     } else { 
      temp = temp.next; 
     } 
    } 
} 
1
void removeDuplicate() 
{ 
    if(head == NULL) 
     return; 
    Node<T>* pPre = head; 
    Node<T>* pCur = pPre->pNext; 
    while (pCur != NULL) 
    { 
     if(pCur->elemet == pPre->elemet) 
     { 
      pPre->pNext = pCur->pNext; 
      pCur = pPre->pNext; 
     } 
     else 
     { 
      pPre = pCur; 
      pCur = pPre->pNext; 
     } 
    } 

} 

我用C++的答案。

0

我在處理java中的相同問題,並在最初掙扎之後提出了非常小的解決方案。請看一下。

Node RemoveDuplicates(Node head) { 
    Node curr = head; 
    if(head==null) 
     return head; 
    while(curr.next!=null){ 
     if(curr.data == curr.next.data) 
      curr.next = curr.next.next; 
     else curr = curr.next; 
    } 
    return head; 
}