获取链接列表以打印数字

Arv*_*ind 3 c++ linked-list data-structures

我想用用户提供的数字填充链表,并将它们再次打印出来.但是,我的实现(如下所示)将只打印出第一个输入数字.我插入列表的头部.你能说出什么问题吗?

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;
    }
Run Code Online (Sandbox Code Playgroud)

Sco*_*tty 5

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

你可以把它作为一个参考到指针,Node*& head.