【问题标题】:Inserting an element at the tail of linked list在链表尾部插入一个元素
【发布时间】:2021-07-23 19:22:24
【问题描述】:

我是数据结构的新手。我终于掌握了在链表开头添加新元素的窍门 但现在还有另一个问题。我已经观看了很多 YouTube 视频,但问题仍未解决。我试图在这个链表的末尾添加一个元素,但是当我这样做时,前两个元素消失了。请帮忙!

#include <iostream>

using namespace std;

class Node{
    public:
    int data;
    Node *next;
    Node(){
        data = 0;
        next = NULL;
    }
};
Node* add_end(Node* a, int new_data){
    Node* ptr, *temp; 
    ptr = a;
    temp = new Node();
    
    temp->data = new_data;
    temp->next = NULL;
    
    while(ptr->next != NULL) {
        ptr = ptr->next;
    }
    
    ptr->next = temp;
    
    return ptr;
}

void print(Node* a){
    while(a != NULL){
        cout << a->data << "  ";
        a = a->next;
    }
}



int main(){
    Node *head = NULL;
    Node *second = NULL;
    Node *third = NULL;
    
    head = new Node();
    second = new Node();
    third = new Node();
    
    head->data = 1;
    head->next = second;
    
    second->data = 2;
    second->next = third;
     
    third->data = 3;
    third->next = NULL;
    
    cout << "Before Adding:\n";
    
    print(head);
    
    head = add_end(head, 4);
            
    cout << "\nAfter Adding: \n";
    
    print(head);
    
    return 0;
}

【问题讨论】:

    标签: c++ linked-list


    【解决方案1】:

    函数add_end应该返回指向头节点的指针。

    您当前的实现返回指向倒数第二个节点的指针,该指针是在添加元素的过程中计算出来的。

    你应该从函数add_end返回a而不是ptr

    另外,当ptrNULL 时,应在循环前返回temp,否则NULL 将被取消引用,可能会导致运行时错误。

    【讨论】:

    • 事实上这个函数也可以是无效的。因为在 'a' 上没有任何修改,所以 head 保持不变。
    • @thomachan "添加到一个空列表" (NULL 传递为a) 这种情况下不支持。
    • 非常感谢。我不认为我会在任何地方得到这样的解释。您能否详细说明您说 ptr 指向倒数第二个元素的那部分?为什么会这样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2020-09-11
    • 2020-11-15
    • 2015-02-08
    相关资源
    最近更新 更多