C ++以更清洁的方式将项目添加到链接列表

时间:2016-10-04 15:37:26

标签: c++ list

我正在尝试将项目添加到列表的前面。基本上,我在这里要做的是:

  • 以空列表开头;

  • 阅读一个数字;

  • 调用函数,其中创建一个新节点来存储数字,下一个指针指向null;

  • 如果列表为空,则此新节点是列表的开头(仅限元素)

  • 如果有更多元素,则此新节点指向列表的头部并成为新头。

我的函数做我想要的(至少我可以在调试器中看到),但在它返回之后我的列表为空并且头再次为空。

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

void insert_front(node *list, int num){
    node * newnode = new (node);
    newnode->data = num;
    newnode->next = nullptr;

    if (list == nullptr)
        list = newnode;
    else{
        newnode->next = list;
        list = newnode;
    }
}

int main()
{
    int n;
    node *head = nullptr;

    cout << "Input numbers to store (0 finishes input): ";
    cin >> n;
    while (n != 0){
        insert_front(head, n);
        cin >> n;
    }
    return 0;
}

也尝试了这个,但它甚至没有编译:

void insert_front(node &lst, int num){
    node *newnode = new node();
    newnode->data=num;
    newnode->next=lst;
    lst=newnode;
}

我故意避免使用OOP,模板,typedef等尽可能地获得“更干净”的代码,以便我能理解一切是如何工作的。

3 个答案:

答案 0 :(得分:2)

您需要引用指针varibable:node *&amp; list

void insert_front(node* &lst, int num){
    node *newnode = new node();
    newnode->data=num;
    newnode->next=lst;
    lst=newnode;
}

如果您没有使用参考文献,那么您将修改您的&#34; lst&#34;指针,所以列表将在离开此函数后继续指向旧前端。 c ++中的参考参数以&#34;&amp;&#34;为前缀。符号。在单个旧C(不是你的情况)中,你需要一个指向指针的指针。

答案 1 :(得分:0)

不要通过引用传递,因为您无法分配它。

node* insert_front(node* list, int val)
{
    node* n = new node();
    n->data = val;
    n->next= list;
    return n;  // return the new head of the list
}

然后插入时:

while (n != 0){
    head = insert_front(head, n);  // head will always change every time you add to the front
    cin >> n;
}

或者,你也可以让你的插入函数更新list以反映新头,但你必须将指针传递给头指针本身:

void insert_front(node** pList, int val)
{
    node* n = new node();
    n->data = val;
    n->next= *pList;
    *pList= n;
}


while (n != 0){
    insert_front(&head, n);  // head will always change every time you add to the front
    cin >> n;
}

答案 2 :(得分:0)

您按值传递列表。

看到这个比喻:

int x;
void modify_x_where_x_is_passed_by_reference( int & x_ref);
void modify_x_where_x_is_passed_by_a_pointer( int * x_ptr);
// Usage
modify_x_where_x_is_passed_by_reference( x );
modify_x_where_x_is_passed_by_a_pointer( &x ); // the address of x

// But when your variable is a pointer!
int * y;
void modify_y_where_y_is_passed_by_reference( int* & y_ref);
void modify_y_where_y_is_passed_by_a_pointer( int* * y_ptr);
// Usage
modify_y_where_y_is_passed_by_reference( y );
modify_y_where_y_is_passed_by_a_pointer( &y ); // the address of y