【发布时间】:2020-04-17 10:55:26
【问题描述】:
我想要解释如何到达链表中的第 N 个节点,以便在第 N 个节点之后插入一个节点我有这段代码,并且在第 n 个节点之后插入一个节点的函数给出为
InsertAfter
我有关于如何在驱动程序主函数中调用函数InsertAfter 的问题,即如果我必须转到头部旁边的节点,我可以写为head -> next 但是,这是为元素编写next -> next 的必要条件超越第二个节点。
有什么简单的方法可以帮助我不要为每个节点写next来跳转到下一个节点。
例如 --> 如果我必须在 7 之后插入节点,我必须写 head-> next-> next 但是有没有什么简单的方法不需要一遍又一遍地 next。
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* next;
};
Node* head = NULL;
void insert(int x)
{
Node* temp = new Node();
temp -> data = x;
temp -> next = head;
head = temp;
}
void display(){
Node* temp;
temp = head;
while(temp != NULL)
{
cout<< temp -> data<< " ";
temp = temp-> next;
}
}
void insertAtLast(int x)
{
Node* temp = new Node();
Node* last = head;
temp -> data = x;
temp -> next = NULL;
if(head == NULL)
{
head = temp;
return;
}
while (last -> next != NULL)
{
last = last-> next;
}
last -> next = temp;
return;
}
void InsertAfter(Node* prev, int data)
{
if(prev == NULL)
{
cout<< "The previous node cannot be NULL" << endl;
return;
}
Node* temp = new Node();
temp -> data = data;
temp -> next = prev -> next;
prev->next = temp;
}
int main() {
insert(3);
insert(1);
insert(7);
insert(2);
insert(9);
cout<<"The linked list is: \n";
display();
cout<< endl;
insertAtLast(6);
display();
std::cout << '\n';
InsertAfter(head->,3);
display();
return 0;
}
【问题讨论】:
-
#include<bits/stdc++.h> using namespace std;永远那样做。 -
我知道。请您只回答被问到的问题。
-
@dukeforever 那如果你知道,你为什么要这么做?
-
"你被要求只回答被问到的问题。" - 1) 这不是答案,而是评论。 2) 你无法控制我制作的 cmets。
-
Node* head = NULL;-->Node* head = nullptr;更好。不要在新代码中使用NULL。你new的东西,但你从来没有delete它--> 内存泄漏。为什么你首先使用手动内存管理?在现代代码中使用容器和/或智能指针。