1

我正在尝试在链接列表的开头添加和打印一个新节点。但是我的代码在用 C++ 打印时没有显示添加的数据。

struct node{
    int data;
    node *next;
};
void add_begin(node *S, int k)
{
    node *T;
    T=new (node);
    T->data=k;
    T->next=S;
    S=T;
}
void print(node *S)
{
    cout<<"Elements of the node :\n";
    while (S->next!=NULL)
    {
        cout<<S->data<<endl;
        S=S->next;
    }
    cout<<S->data<<endl;
}
4

1 回答 1

1

I am assuming that you would be calling this function passing in a node which is the head of a list and an int which is the new data and are expecting the node you passed in to be updated to the new node.

Unfortunately that is not what is happening. Inside the function add_begin it has its own pointer to the first node in the list so when you update it with S=T only pointer in the function is updated, not the one you passed in as well.

If you want to update the pointer you pass in you should pass it by reference (void add_begin(node *&S, int k)) or return the new node pointer from the function and assign it the external pointer manually.

于 2013-08-18T17:26:04.730 回答