I have a code, which seems to be working but I am failing to get the values stored in the linked list between the first and the last node, the pointers in between are skipped? And dereferencing these skipped pointer gives me a segfault, here is the code
#include<iostream>
#include <new>
using namespace std;
class list{
int value;
list* next;
public:
list(int a=0, list* b=0) {value=a;next=b;}
//~list() {delete next;}
void newnode(int a, list* tmp) {
tmp->next=new list;
tmp=tmp->next;
cout<<"Address of next: "<<tmp<<'\n';
tmp->value=a;
}
void printlist (list* regist){
list* tmp;
tmp=regist;
cout<<tmp->value<<'\n';
while(tmp->next != 0){
tmp=tmp->next;
cout<<tmp->value<<'\n';
cout<<"Address of next: "<<tmp<<'\n';
}
}
};
int main() {
int first;
cout<<"Enter value for origin: \n";
cin>>first;
list* root=new list(first);
list* tpo=root;
cout<<"How many numbers to add? \n";
int choice;
cin>>choice;
int num;
while(choice) {
cout<<"Enter value: \n";
cin>>num;
root->newnode(num, tpo);
choice--;
}
cout<<"Do you want me to show you these values, type 1 for yes and 0 for no: \n";
cin>>choice;
if(choice) {
root->printlist(root);
}
}
- On printing the values why does it skip these pointer(nodes) in between?
- Are the in between nodes being pointed to destroyed? If so, commenting the destructor, should do the trick, right?
What am I doing wrong?
root->newnode(num, tpo);never updatesrootortposo each new value replaces the previous one