使用链表.为什么我的插入功能不起作用?
Working with linked lists. Why my insert function is not working?
我正在尝试插入数字,这些数字是在已经组成的列表中扣除两个邻居的结果。
#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
永远不会变成假的。
相关文章:
- 为什么我的打印功能不起作用?链表
- 虚拟功能不起作用
- C++插入排序错误功能不起作用
- 使用链表.为什么我的插入功能不起作用?
- C 所有质数功能不起作用
- 朋友功能不起作用(语法错误)
- Winpcap:暂停/停止嗅探pcap_breakloop功能不起作用
- C 类是功能不起作用的参数
- 排序功能不起作用
- TIM6,基本时间生成功能不起作用
- 二进制树级别明智的打印功能不起作用
- glutkeyboardfunc呼叫功能不起作用
- 二进制搜索功能不起作用
- C++ 如果要替换的句子具有"+"符号,则替换字符串功能不起作用
- 字符串返回功能不起作用 - 'identifier is underfined'
- 为什么此拆分功能不起作用
- 为什么 openCV 的转换功能不起作用?
- fscanf 的包装功能不起作用
- 海湾合作委员会 - 功能不起作用(但其他警告正在起作用)
- 排序功能不起作用(字符串比较问题)