gpt4 book ai didi

c++ - 在链表的第 n 个位置插入节点(无法理解我的代码)

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:39:33 24 4
gpt4 key购买 nike

无法理解 [else 语句] block 中的步骤。请有人帮助我。我正在尝试在第 n 个位置插入一个节点,请记住,除非已创建第 (n-1) 个节点,否则无法创建第 n 个位置的节点。

编辑:-现在我已经发布了完整的代码(工作),

#include<iostream>
using namespace std;



struct Node{
int data;
Node*next ;
};

void insertlinkedlist(Node**head,int data,int position)
{
int k = 1;

Node *p,*q,*newNode;

newNode=(Node*)malloc(sizeof(Node));
if(!newNode)
{
cout<<"Memory leak";
return;
}

newNode->data = data;
p=*head;

if(position ==1)
{
newNode ->next = p;
*head = newNode;
}

else {
while(p!=NULL&k<position){
k++;
q=p;
p = p->next;
}
q->next = newNode;
newNode ->next = p;
}
}

void display(Node*head)
{
Node*ptr = head;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->next;
}
}


int main(){
Node*head = NULL;
insertlinkedlist(&head, 34, 1);
insertlinkedlist(&head, 3, 2);
insertlinkedlist(&head, 13, 3);

display(head);

cout<<endl;


}

输出

34 3 13

最佳答案

当第一个位置没有插入元素时,执行 else 语句。在您的代码中引用 1。我认为用 0 声明第一个位置是更好的方法。
while 语句 p!=null当指针有效时返回 true (=0)。该值与 k<position 的返回值进行按位与运算。 .因此,当您位于链表的最后一个元素或指定位置时,while 语句将中断。
执行 while 语句后,您在末尾或 q 的实际指定位置插入新节点,这在 while 语句中计算。之后,在 newNode 之后插入下一个元素.想象在位置 3 有一个新元素。然后这个元素在位置 3,并且 3 之后的所有内容都从位置 4 开始。

关于c++ - 在链表的第 n 个位置插入节点(无法理解我的代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54105694/

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