使用循环在链接列表的前面插入一个节点

Insert a node in the front of a Link list using loop

本文关键字:节点 一个 插入 前面 循环 链接 列表      更新时间:2023-10-16

我试过这段代码。此代码的输出即将到来 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 工作。

相关文章: