c++ - 如何在链表中动态创建新节点C++

标签 c++ data-structures linked-list nodes

谁能告诉我这是否是链表的基本思想?这种方法的优点和缺点是什么?在 C++ 中实现链表时的最佳实践是什么?我对数据结构不熟悉,所以这是我的第一个方法。如果有更好的方法来做同样的事情,请告诉我。此外,如何动态创建节点而不对其进行硬编码?谢谢。

#include <iostream>
#include <string>

using namespace std;
struct node {
    int x;
    node *next;
};

int main()
{

    node *head;
    node *traverser;


    node *n = new node;                 // Create first node
    node *t = new node;                 // create second node

    head =n;                            //set head  node as the first node in out list.
    traverser = head;                   //we will first begin at the head node.

    n->x = 12;                          //set date  of first node.
    n->next = t;                        // Create a link to the next node

    t->x = 35;                          //define date  of second node.

    t->next = 0;                        //set pointer to null if this is the last node in the list.


    if ( traverser != 0 ) {                 //Makes sure there is a place to start
        while ( traverser->next != 0 ) {
            cout<< traverser->x;            //print out first data member
            traverser = traverser->next;    //move to next node
            cout<< traverser->x;            //print out second data member

        }
    }
    traverser->next = new node;  // Creates a node at the end of the list
    traverser = traverser->next; // Points to that node
    traverser->next = 0;         // Prevents it from going any further
    traverser->x = 42;
}

最佳答案

出于教程目的,您可以计算此示例:

#include <iostream>

using namespace std;

struct myList
{
    int info;
    myList* next;
};

int main()
{
    //Creation part
    myList *start, *ptr;
    char ch = 'y';
    int number;
    start = new myList;
    ptr = start;
    while (ptr != NULL)
    {
        cout << "Enter no. ";
        cin >> ptr->info;
        cout << "Continue (y/n)? ";
        cin >> ch;
        if (ch == 'y')
        {
            ptr->next = new myList;
            ptr = ptr->next;
        }
        else
        {
            ptr->next = NULL;
            ptr = NULL;
        }
    }

    //Traversal part begins
    cout << "Let's start the list traversal!\n\n";
    ptr = start;
    while (ptr!=NULL)
    {
        cout << ptr->info << '\n';
        ptr = ptr->next;
    }
}

它会为您想要添加的元素动态分配内存。

关于c++ - 如何在链表中动态创建新节点C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27736592/

相关文章:

c++ - 使用嵌套类解析模板

c++ - 模板参数是否在编译时评估?

algorithm - 向后打印一个没有递归的简单链表,最多两次,使用常量额外内存,保持原样

javascript - 关闭和垃圾收集 : most efficient way to remove consecutive nodes from a linked list

C++ 问题: "Unresolved external ' UberList<int>::Iter::Iter( )' referenced from C:\USERS\HOME\CPPTEST\UBERLIST.OBJ"

c++ - 在 C++ 中逐行读取文件(每行有一个字符串和几个 int 值)?

c++ - 标准 C++14 中零大小数组的解决方法?

java - 数据结构复习 (Java)

algorithm - graph - 如何找到 G 的最大诱导子图 H,使得 H 中的每个顶点的度数≥ k

python - Django 模型 - 如何在事后通过 PK 过滤掉重复值?