2013-05-04 166 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; 
} 
相关问题