gpt4 book ai didi

c++ - 使用循环在链表的前面插入一个节点

转载 作者:行者123 更新时间:2023-11-30 02:31:37 25 4
gpt4 key购买 nike

我试过这段代码。这段代码的输出是 1 10 9 8 7 6 5 4 3 2。但我想要输出 10 9 8 7 6 5 4 3 2 1。我不明白我的错是什么。我看到这个问题之前已经问过,但是为了澄清我的概念,我又问了这个问题。对此代码有更好的解决方案。

    #include <iostream>
using namespace std;
struct NODE
{
int data;
NODE *next;
};
int main()
{
int i,j=0;
NODE *start=NULL,*ptr,*temp;
for (i=1; i<=10; i++)
{
ptr = new NODE;
ptr->data=i;
if(start==NULL)
{
ptr->next=NULL;
start=ptr;
}
else
{
ptr->next=start->next;
start->next=ptr;
}
}
temp=start;
for ( temp = start; temp; temp = temp->next )
cout << temp->data << ' ';
return 0;
}

最佳答案

循环有不必要的逻辑。它可以简单地是:

   for (i=1; i<=10; i++)
{
ptr = new NODE;
ptr->data=i;

// It doesn't matter what start is.
// The new NODE is added to the front.
ptr->next=start;

// Make the new NODE the front(start).
start=ptr;
}

http://ideone.com/y62FnG 查看它的工作情况.

关于c++ - 使用循环在链表的前面插入一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37464956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com