【问题标题】:Swapping value in linked list交换链表中的值
【发布时间】:2018-07-14 11:29:17
【问题描述】:

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

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

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

【问题讨论】:

  • 或者,@H.S,假设语言标签是错误的。您不能“混合”C 和 C++ 代码;它是 C 或 C++。而且它似乎编译了 Occam's Razor 说它是具有 C 编码风格的 C++。
  • “你不能混合”——至少不能在同一个编译单元中......
  • “导致错误” - 哪种错误?
  • @Aconcagua 后期显示不显示nad返回值过百万
  • 我不知道它的哪一部分是 C++,但我确实尝试将 = new Nodes() 更改为 malloc() 但仍然不起作用...关于我应该更改的任何建议?

标签: c++ sorting linked-list


【解决方案1】:
if(curr->value > next->value && next != NULL)
//                              ^^^^^^^^^^^^   too late!

a &amp;&amp; b 首先检查 a,并且只有当 a 为真时,才会评估 b - 所以检查 next 是否为 nullptr 只有在 已经 访问过 *next 之后才会评估(如果有的话,如果next nullptr,程序可能已经崩溃了)。所以反过来检查:

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

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

【讨论】:

  • 哇真的谢谢老兄,你帮了我这么多,尽管这样的基础知识真的会有影响
猜你喜欢
  • 2017-12-07
  • 2018-11-05
  • 2022-01-07
  • 2022-01-10
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 2013-02-25
相关资源
最近更新 更多