【问题标题】:Linked List: Inserting a node at the end链表:在末尾插入一个节点
【发布时间】:2020-11-15 02:27:00
【问题描述】:

我一直在学习数据结构,目前正在使用链表。我试图在链表的末尾添加一个节点,但无法找出正确的逻辑。我试过在开头插入一个节点,效果很好。

这是代码:

#include <bits/stdc++.h>
using namespace std;

class Node {
    public:
        int data;
        Node* next;
};

Node* head; // global
void Insert(int data) {
    Node* temp = new Node();
    temp -> data = data;
    temp -> next = head;
    head = temp;
} // insert an integer

void Print(){
    Node* temp = head;
    cout << "List is: ";
    while (temp != NULL) {
        cout << temp -> data << " ";
        temp = temp -> next;
    }
    cout << endl;
} // print all elements in the list

void Delete(int n){
    Node* temp1 = head;
    if(n == 1) {
        head = temp1 -> next; // head now points to second node
        delete temp1;
        return;
    }
    int i;
    for(i = 0; i < n-2; i++)
        temp1 = temp1 -> next;
        // temp1 points to (n-1)th Node
    Node* temp2 = temp1 -> next; // nth Node
    temp1 -> next = temp2 -> next; // (n+1)th Node
    delete temp2; // delete temp2
} // Delete node at position n

int main() {
    head = NULL; // empty list
    Insert(2);
    Insert(4);
    Insert(6);
    Insert(5); // List: 2,4,6,5
    Print();
    int n;
    cout << "Enter a postion: " << endl;
    cin >> n;
    Delete(n);
    Print();
}

此代码删除第 n 个位置的节点。这里的节点是从头开始添加的,我正在尝试找出从最后插入它的逻辑。

对此的任何建议和建议都会非常有帮助。

提前谢谢你。

【问题讨论】:

标签: c++ data-structures linked-list singly-linked-list


【解决方案1】:

Play with the code.

void insert_end(int data) {
    Node* temp = new Node();  // 1
    temp->data = data;
    temp -> next = nullptr;
    
    Node* n = head;
    if (!n) {         // 2
        head = temp;
        return;
    }
    while(n->next) {  // 3
        n = n->next;
    }
    n->next = temp;
}

方法的简要说明:

1: 你创建一个新的Node 并设置数据。

2: 检查列表是否为空。如果是,则在头部插入新元素。

3: 如果列表不为空,则读取列表的下一个元素,直到找到列表中的最后一个节点。如果你在这里写while(n)...,你会到达列表的末尾,这意味着nullptr,代码会中断。

【讨论】:

  • 更改并添加此功能后,我正在尝试打印它,但它无法在控制台中显示任何输出
  • 点击Play with code。那里的实现打印整个列表,包括新添加的元素
  • @User12547645 你应该测试headnullptr 否则会崩溃。
猜你喜欢
  • 2015-02-08
  • 2015-12-14
  • 2011-08-13
  • 1970-01-01
  • 2016-10-11
  • 2021-05-23
相关资源
最近更新 更多