首页 > 解决方案 > 交换链表中的值

问题描述

我想在一个链表中排序,在不弄乱地址的情况下更改节点之间的值,当我设置交换条件时,我不能在那里放任何代码。我尝试插入 printf 并更改值(除了交换)并导致错误。

我想知道我的代码的哪个部分有问题以及如何在不对结构进行太多更改的情况下解决此问题,此代码是根据我所学的知识进行实验的,谢谢提前

    #include <stdio.h>
    #include <stdlib.h>

    typedef struct Nodes
    {
        int value;
        Nodes* next,*prev;
        Nodes(int val)
        {
            value = val;
            next = prev = NULL;
        }
    }Nodes;
    Nodes *head,*tail,*curr;

    void display()
    {
        curr = head;
        while(curr)
        {
            printf("%d ",curr->value);
            curr=curr->next;
        }
    }

    void swap(Nodes *a,Nodes *b)
    {
        int temp = a->value;
        a->value = b->value;
        b->value = temp;
    }
    void sort()
    {
        curr = head;
        while(curr)
        {
            Nodes *next = curr->next;
            if(curr->value > next->value && next != NULL)
            {
    //          this space cant code anything or it will break
    //          swap(curr,next);
            }
            curr = next;
        }
    }

    void insert(int val)
    {
        if(!head)
        {
            head = tail = new Nodes(val);
        }
        else
        {
            curr = new Nodes(val);
            tail->next = curr;
            curr->prev = tail;
            tail = curr;
        }
    }

    int main()
    {
        insert(8);
        insert(3);
        insert(20);
        display();
        puts("");
        sort();
        display();
        return 0;
    }

标签: c++sortinglinked-list

解决方案


if(curr->value > next->value && next != NULL)
//                              ^^^^^^^^^^^^   too late!

a && b首先检查 a 并且仅当 a 为真时才对 b 进行评估——因此仅在已经访问过next之后nullptr才评估存在的检查(如果有的话,程序很可能在 if is之前崩溃)。所以反过来检查:*nextnext nullptr

if(next && curr->value > next->value)

那么你的排序算法是不完整的,看起来很像冒泡排序,但只有一个“冒泡”上升......


推荐阅读