#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;
}我无法理解为什么我要得到这个代码的分段错误。此代码是从未排序链接列表中删除重复元素。
I使用前一个指针存储内环指针之前的节点,当发现内环节点数据等于外环节点数据时,使前一个指针指向内环节点的下一个指针,释放内环节点。
发布于 2015-07-07 05:12:30
for(ptr=head;ptr->next!=NULL;ptr=ptr->next){应该是
for(ptr=head;ptr!=NULL;ptr=ptr->next){它失败了,因为在最后只剩下两个12s,而ptr正指向其中一个。接下来是null,所以输入迭代。在该迭代中,您将删除第二个12,因此ptr的下一个现在为null。然后迭代结束,将ptr设置为ptr->next,因此ptr本身变为null,然后检查ptr->next是否为null,然后在那里崩溃。
编辑:如果您想跳过最后一个元素,请执行
for(ptr=head;ptr && ptr->next!=NULL;ptr=ptr->next){发布于 2015-07-07 05:13:18
for(ptr=head;ptr->next!=NULL;ptr=ptr->next)在这一行中,当您说ptr->next!=NULL时,最后一个节点的空指针将被取消引用。这会产生分段错误,因为您试图访问空指针。
因此,只需将第二个条件作为ptr!=NULL。这就足够了,因为在ptr=ptr->next循环的第三个条件下执行for已经足够了。
发布于 2015-07-07 05:04:33
for循环中的这个条件ptr->next!=NULL是有问题的。
for(ptr=head;ptr->next!=NULL;ptr=ptr->next)它将取消对最后一个节点的NULL指针的引用。它应该是:
for(ptr=head;ptr!=NULL;ptr=ptr->next)https://stackoverflow.com/questions/31260018
复制相似问题