使用循环在链接列表的前面插入一个节点
Insert a node in the front of a Link list using loop
我试过这段代码。此代码的输出即将到来 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 工作。
相关文章:
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 在C++的链表末尾插入一个节点
- 节点是否为空,即使它有一个值?
- 在解决链表问题时创建一个额外的节点是一个好习惯吗?
- 插入一个基本的单向链表节点似乎破坏了我的 c++ 代码?
- 在单链表前面添加一个节点后,我无法遍历每个节点
- 删除链接列表中剩余的最后一个节点
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 给一个图 G 找到此图中的所有节点 blob,以便 node.color 属性 = 特定颜色
- 如何在级别上打印树,给定一个结构,该结构保存节点的值及其父节点的值,对于树中的每个节点
- 为什么T是未定义的?我正在尝试实现一个用于双链表的节点类,它不喜欢我使用友元运算符后的T
- C++中是否有一个函数可以为您获取指向该节点的所有指针的地址空间
- C++循环链表删除,计数从下一个节点开始
- 在由邻接列表表示的树中查找节点到另一个给定节点之间的路径
- 如何在 c++ 中实现 avl 树,每个节点都是另一个 avl 树
- 使用异或实现双链表,每个节点一个指针