簡體   English   中英

我想成對交換鏈表項,我的代碼給了我Segmentation Fault

[英]I want to swap the linkedlist terms pairwise, my code is giving me Segmentation Fault

我想成對交換鏈表術語。

這是我的代碼。 它給了我細分錯誤核心

#include <stdio.h>
#include <stdlib.h>
struct node 
{
    int data;
    struct node *next;
}*head;
void insert(struct node *n)
{
    int  num;
    printf("Enter a number : ");
    scanf("%d",&num);
    struct node *temp;
    temp=(struct node *)malloc(sizeof(struct node));
    temp->data=num;
    if(n==NULL)
    {
        head=temp;
        head->next=NULL;
    }
    else
    {

        temp->next=head;
        head=temp;
    }

}
int main()
{
    struct node *n;
    head=NULL;
    n=head;
    int i;
    for(i=0;i<6;i++)
    {

        insert(n);
        n=head;
    }
    display(n);
    pairswap(n);
    display(n);

}
void display(struct node *n)
{
    struct node *temp;
    temp=n;
    while(temp!=NULL)
    {
        printf("%d ",temp->data);
        temp=temp->next;
    }
}
void pairswap(struct node *n)
{
    struct node *temp,*temp1,*temp2;
    temp=n;
    temp1=temp->next;
    while(temp!=NULL)
    {
        int tempnum;
        tempnum=temp->data;
        temp->data=temp1->data;
        temp1->data=tempnum;
        if(temp==n)
        {
            head=temp;
            head->next=temp1;
        }
        else
        {
            temp2->next=temp;
            temp2->next->next=temp1;
        }
        temp2=temp1;
        temp=(temp->next)->next;
        temp1=temp->next;
    }
    n=head;
}

請了解調試器。

在列表末尾的(temp->next)->next是NULL,您將其放入變量temp中。

在進行此分配temp1=temp->next ,您需要檢查temp是否為NULL並采取適當的措施。

問題是pairswap函數。 在while循環中,您使用以下條件:while(temp!= NULL)

並在循環中分配:temp =(temp-> next)-> next

由於您嘗試取消引用NULL指針,因此第二個節點將崩潰。

使用以下條件:while((temp-> next)-> next!= NULL)或while(temp1-> next!= NULL)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM