使用链表.为什么我的插入功能不起作用?

Working with linked lists. Why my insert function is not working?

本文关键字:功能 不起作用 插入 我的 链表 为什么      更新时间:2023-10-16

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

#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->next;

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

。并重复,直到你明白为什么p->next!=NULL永远不会变成假的。