分段错误删除未排序链表中的重复元素

时间:2015-07-07 04:55:24

标签: c++ pointers linked-list segmentation-fault

#include<iostream>
#include<stdlib.h>
using namespace std;

struct node{

    int data;
    struct node* next;

};

struct node* head;

void traversalLinkedList(struct node* ptr){

    if(ptr==NULL) {cout<<"null hain bhai"<<endl; return;}

    while(ptr!=NULL){
        cout<<ptr->data<<" ";
        ptr=ptr->next;
    }

}

void push(int d){

    //at the front of linked list

    struct node* temp=(struct node*) malloc(sizeof(struct node));

    temp->data=d;
    temp->next=head;

    head=temp;

}


int main(){

    head=NULL;

  //removing duplicates from linked list

  push(10);
  push(11);
  push(12);
  push(11);
  push(11);
  push(12);
  push(10);

  traversalLinkedList(head);

  struct node *ptr;

  struct node* prev;

  struct node* qtr;

  for(ptr=head;ptr->next!=NULL;ptr=ptr->next){

    prev=ptr;

    for(qtr=ptr->next;qtr!=NULL;){


      if(ptr->data==qtr->data){
        //means duplicate nodes
        prev->next=qtr->next;
        free(qtr);
        qtr=prev->next;
      }

      else{
        prev=qtr;
        qtr=qtr->next;
      }



    }

  }

  cout<<endl;

  traversalLinkedList(head);

  cout<<endl;




    return 0;
}

我无法理解为什么我会为此代码获取分段错误。此代码是从未排序的链表中删除重复元素。

解释 我发现内部循环节点数据等于外部循环节点数据时,我使用前一个指针存储内部循环指针之前的节点,前一个指针指向内部循环节点接下来指针和内部循环节点被释放。

3 个答案:

答案 0 :(得分:2)

for(ptr=head;ptr->next!=NULL;ptr=ptr->next)

在这行中,当你说ptr-> gt; next!= NULL时,将为最后一个节点取消引用空指针。由于您尝试访问空指针,因此会出现分段错误。

所以,只需将第二个条件设为ptr!=NULL即可。这就足够了,因为你在ptr=ptr->next循环的第三个条件下正在进行for

答案 1 :(得分:1)

for循环中的这种情况ptr->next!=NULL存在问题。

for(ptr=head;ptr->next!=NULL;ptr=ptr->next)

它将取消引用最后一个节点的NULL指针。它应该是:

for(ptr=head;ptr!=NULL;ptr=ptr->next)

答案 2 :(得分:1)

for(ptr=head;ptr->next!=NULL;ptr=ptr->next){

应该是

for(ptr=head;ptr!=NULL;ptr=ptr->next){

它失败了,因为最后只剩下两个12,而ptr指向其中一个。它的下一个不为空,因此您输入迭代。在那次迭代中你删除第二个12,所以ptr的下一个现在是null。然后迭代结束,你将ptr设置为ptr-&gt; next,所以ptr本身变为null,然后检查ptr-&gt; next是否为null,然后崩溃。

编辑:如果你想跳过最后一个元素,请执行

for(ptr=head;ptr && ptr->next!=NULL;ptr=ptr->next){