gpt4 book ai didi

c++ - 链表:在最后插入一个节点

转载 作者:行者123 更新时间:2023-12-01 14:47:15 28 4
gpt4 key购买 nike

我一直在学习数据结构,目前正在使用链表。我正在尝试在链表的末尾添加一个节点,但无法为它找出正确的逻辑。我试过在开始处插入一个节点,它工作正常。
这是代码:

#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个位置的节点。这里的节点是从头开始添加的,我正在尝试弄清楚从头开始插入它的逻辑。
关于此的任何建议和建议将非常有帮助。
预先感谢您。

最佳答案

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:如果列表不为空,则读取列表的下一个元素,直到列表中有最后一个Node。如果您在此处编写 while(n)...,您将到达列表的末尾,这意味着 nullptr和代码将中断。

关于c++ - 链表:在最后插入一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63086826/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com