#include<iostream>
class ListNode{
public:
int content;
ListNode *pointerToNext;
};
void addElement(int input, ListNode** pHead){
ListNode *temp;
temp=new ListNode;
temp->content=input;
temp->pointerToNext=*pHead;
*pHead=temp;
}
void deleteElements(int input, ListNode** pHead){
for(int i=0; i>input; --i){
ListNode *temp2;
temp2=*pHead;
temp2=temp2->pointerToNext;
ListNode *temp3;
temp3=*pHead;
*pHead=temp2;
delete temp3;
}
}
int main(){
std::cout<<"Insert a list of integers greater than or equal to -9";
std::cout<<std::endl;
std::cout<<"(inserting -9 will end the list)" <<std::endl;
std::cout<<"inserting a negative number, z, will delete the last |z| numbers
in your sequence." <<std::endl;
int userInput;
std::cin>>userInput;
ListNode *head;
head=new ListNode;
head->content=userInput;
head->pointerToNext=nullptr;
while(userInput != -9){
std::cin>>userInput;
if(userInput >= 0){
addElement(userInput, &head);
}
if(userInput < 0 && userInput > -9){
deleteElements(userInput, &head);
}
}
return 0;
}
I am trying to make the code a little better by replacing the void deleteElements(int input, ListNode** pHead) with this function
1 2 3 4 5 6 7 8
void deleteElements(int input, ListNode** pHead){
for(int i=0; i>input; --i){
ListNode *temp2;
temp2=*pHead;
*pHead=*pHead->pointerToNext; //this is where I get compiler error
delete temp2;
}
}
1. I am trying to make head into the second node so that I can delete the first node, but I can't do *pHead=*pHead->pointerToNext;. Am I doing it wrong or is it impossible to do?
2. In my void deleteElements(int input, ListNode** pHead) function I tried to add delete temp; as the last line because each time the function is called it is creating another node called temp, so if the original temp isn't deleted does this cause a memory leak? When I try this the code compiles but I get a "segmentation fault (core dumped)" error.
1. You should be able to use ++*pHead in order to move to the next pointer.
2. void deleteElements(int input, ListNode** pHead) doesn't have a member named temp. void addElement(int input, ListNode** pHead) does though. You can't really delete something that isn't there.
*pHead ends up pointing to the same location as temp after addElement so if you delete temp, you are effectively setting *pHead to NULL.