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

标签 c++ list hyperlink insert

我试过这段代码。这段代码的输出是 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/

相关文章:

c++ - 来自 codesampler 的 Direct3D (DirectX 9.0) 代码示例

c - 抛出异常 : read access violation. **head** 为 0xCCCCCCCC。发生

c++ - OpenGL 三角形 strip 上不需要的颜色褪色问题。想要在三角形上获得统一的颜色

c++ - 可变与惰性评估

转换为字符串时, float 的 Python 列表以 ':' 结尾

python - 在 Python 中线性化列表的最短方法

html - 为什么 .css 文件没有改变字体系列?

javascript - 显示 xml 数据的链接

html - 样式列表按钮

c++ - 我如何 typedef 基类的成员模板?