c - 我想成对交换链表项,我的代码给出了段错误

标签 c linked-list

我想成对交换链表项。

这是我的代码。它给了我段错误核心转储

#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;
}

最佳答案

请了解调试器。

列表末尾某处的值 (临时->下一个)->下一个 是 NULL,您将其放入变量 temp 中。

在进行此赋值之前temp1=temp->next,您需要检查 temp 是否为 NULL 并采取适当的操作。

关于c - 我想成对交换链表项,我的代码给出了段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21682845/

相关文章:

arrays - 警告 : format ‘%s’ expects type ‘char *’ , 但参数 2 的类型为 ‘char (*)’

c - Linux下segfault自重启程序

java - 如何获取链表中的Node组件?

java - 创建的链接列表未返回正确的索引

java - Java删除重复的链表

c++ - 遍历多链表?

c++ - 链表c++代码错误

c - fgetc 阻塞 : problem with reading from a pipe

c - 关于GThread和文件复制的问题

比较和解释两个时间计数器