I am trying to insert numbers which are a result of deduction of two neighbors in already made up list.
#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;
}
I expected that my updated list will contain these numbers which should be placed between every two numbers in the original list but when my program encounters the insert function it is just running and never finishes. Example: Original list: 1 5 8 12 30 Updated list: 1 4 5 3 8 4 12 18 30
head=insert(head);doesn't make sense at all. What iscreateList()?createListis missing. Please add complete code to get help and also I suggest you to do some debugging before posting.std::list? If this is an assignment then imho you should mention it in the question, becuase typically they come with all sorts of strange requirementscreateElement()should actually be part of the initialization inElement::Element().