gpt4 book ai didi

c++ - 使用链表。为什么我的插入功能不起作用?

转载 作者:行者123 更新时间:2023-11-28 01:18:54 25 4
gpt4 key购买 nike

我正在尝试插入数字,这些数字是在已经构成的列表中扣除两个邻居的结果。

        #include<iostream>

using namespace std;

struct Element{
int x;
Element* next;
};

Element* createList(){
int i,n;
Element *head=NULL,*p=NULL;
cout<<"How many elements: ";
cin>>n;
for(i=0;i<n;i++){
if(i==0) {
head=new Element();
p=head;
}
else{
p->next=new Element();
p=p->next;
}
cout<<"Value: ";
cin>>p->x;
}
p->next=NULL;
return head;
}

void printList(Element* head){
Element* p=head;
cout<<"List values: "<<endl;
while(p!=NULL){
cout<<p->x<<" ";
p=p->next;
}
cout<<endl;
}

Element* createElement(int x){
Element* element=new Element();
element->x=x;
element->next=NULL;
return element;
}


Element* insert(Element* head){
Element *p=head,*temp=NULL;
while(p->next!=NULL){
temp=createElement(p->next->x - p->x);
temp->next=p->next;
p->next=temp;
p=p->next;
}
return head;
}


int main(){
Element* head=NULL;
head=createList();
printList(head);
head=insert(head);
printList(head);
return 0;
}

我希望我的更新列表将包含这些数字,这些数字应该放在原始列表中的每两个数字之间,但是当我的程序遇到插入函数时,它只是在运行并且永远不会完成。例子: 原始列表:1 5 8 12 30 更新列表:1 4 5 3 8 4 12 18 30

最佳答案

画出来(铅笔和纸比 ASCII 好,但很难张贴在这里):

temp->next = p->next 之后:

      head
|
v
+---+ +---+
p -->| ------>| -----> ...
+---+ +---+
^
+---+ |
temp -->| ------+
+---+

p->next=temp;

      head
|
v
+---+ +---+
p -->| ---+ | -----> ...
+---+ | +---+
v ^
+---+ |
temp -->| ------+
+---+

p=p->下一步;

      head
|
v
+---+ +---+
| ---+ | -----> ...
+---+ | +---+
v ^
+---+ |
temp -->| ------+
+---+
^
|
p

... 并重复,直到您明白为什么 p->next!=NULL 永远不会变为 false。

关于c++ - 使用链表。为什么我的插入功能不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57608294/

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