c++ - 获取链接列表以打印数字

标签 c++ data-structures linked-list

我想用用户提供的数字填充一个链表,然后再打印出来。但是,如下所示,我的实现只会打印出第一个输入数字。我插入列表的头部。你能告诉我哪里出了问题吗?

struct Node 
{
  int data; 
  Node* next;
};

Node newNode(int num, Node *next_node)
{
    Node node;
    node.data = num;
    node.next = next_node;
    return node;
}

void headInsert(Node* head, int num)
{
    Node* tmp;  
    tmp  = new Node;
    tmp->data = num;
    tmp->next = head;
    head = tmp;
}

int main(int argc, char* argv[])
{

    if (argc < 2)
    {
        std::cout<< "No input for linked list!! \n" <<
                    "Usage: ./linkedlist 2 3 567 12 .. etc."
                 <<"\n";
        return 0;
    }

    Node *head, *temp;
    head = new Node;
    head->data = atoi(argv[1]);
    head->next = NULL;

    headInsert(head, atoi(argv[2]));
    headInsert(head, atoi(argv[3]));

    temp = head;

    while(temp != NULL) 
    {
        std::cout << temp->data<< " ";
        temp = temp->next;
    }

        return EXIT_SUCCESS;
    }

最佳答案

headInsert()中,head = tmp;只改变局部变量head

您可以将其作为对指针的引用Node*& head 传递。

关于c++ - 获取链接列表以打印数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11615721/

相关文章:

c++ - 帮助链接列表函数....重载流操作和获取和设置函数 C++

c++ - 面向对象 : How to Choose from a Number of Implementations

algorithm - 二叉搜索树可以实现一个Map吗?

performance - 更快地构建 trie

java - 多线程服务器

c - 菜单式程序

linked-list - 在单链表中查找循环

c++ - 肯定是无效的指针范围

c++ - 从二进制文件(进入类)读取 double - 小数不显示

c++ - 嵌套类的不完整类型