首页 文章

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

提问于
浏览
2

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

  • 从空列表开始;

  • 读一个数字;

  • 调用函数,其中创建新节点以存储数字,并且下一指针指向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

    您需要对指针varibable的引用:node *&list

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

    如果你不使用引用,你将修改你的“lst”指针的副本,所以在离开这个函数后列表将继续指向旧的前面 . c中的参考参数以“&”符号为前缀 . 在单个旧C(不是你的情况)中,你需要一个指向指针的指针 .

  • 2

    您按值传递列表 .

    看到这个比喻:

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

相关问题