3

我想用用户提供的数字填充一个链接列表,并让它们再次打印出来。但是,如下所示,我的实现只会打印出第一个输入数字。我在列表的开头插入。你能说出什么是错的吗?

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;
    }
4

1 回答 1

5

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

您可以将其作为引用指针传递,Node*& head.

于 2012-07-23T15:37:19.637 回答