
Algorithms Algorithms and Data Structures  Analysis, Graph, Search, String, Sorting, Merge, Compression, Optimization, Quantum 
 LinkBack  Thread Tools  Display Modes 
January 23rd, 2012, 09:06 AM  #1 
Joined: Jan 2012 Posts: 2  Question about linked list
I'm learning Linked lists and i'm having trouble adding numbers to the back of the list. I can only add up to two, for example: 1, 2, then, if i add a third number, it will replace the second. example: 1, 3, What am i doing wrong? Code: #include <iostream> #include <conio.h> using namespace std; class list { private: struct node { int data; node *next; }*head; public: list() : head(NULL) {} ~list(); void push_back(int &d); void print() const; }; list::~list() { node *temp = head; node *tmp2; while(temp != NULL) { tmp2 = temp; temp = temp>next; delete tmp2; } cout << "All nodes destroyed..." << endl; } void list::push_back(int &d) { if(head == NULL) { head = new node; head>data = d; head>next = NULL; } else { node *temp = head; node *t; t = new node; t>data = d; t>next = NULL; temp>next = t; } } void list::print() const { if(head == NULL) { cout << "list is empty..." << endl; _getch(); } else { node *temp = head; while(temp != NULL) { cout << temp>data << ' '; temp = temp>next; } } cout << endl << endl; } int main() { list ll; int num; int choice; do { cout << "Enter choice:" << endl; cout << "1. push_back." << endl; cout << "2. print list." << endl; cout << "3. Quit. " <<endl; cout << ">> "; cin >> choice; switch(choice) { case 1: cout << "Enter number: "; cin >> num; cout << endl; ll.push_back(num); num = 0; break; case 2: ll.print(); break; case 3: break; } }while(choice != 3); _getch(); return 0; } 
My Computer Forum is free to register and we welcome everyone! 
February 16th, 2012, 05:49 AM  #2 
Joined: Feb 2012 Posts: 1  Re: Question about linked list
Hi A really simple way to do this is like this: void list:ush_back(const int &d) { node* newNode = new node; newNode>data = d; newNode>next = head; head = newNode; } Note some changes. Parameter is const which means you can do this for example: list ll; ll.push_back(1); What happens is that head is always the last element added to the list. It is behaving like a stack. If this behaviour is fine for your application then this is the simplest implementation. Angus 

Tags 
linked, list, question 
Thread Tools  
Display Modes  

Similar Threads  
Thread  Thread Starter  Forum  Replies  Last Post 
C++ question...awesome question....challenging too !!!  Vishal Srinivas  Programming  1  July 3rd, 2013 08:25 PM 
List of numbers  Quantum++  Algorithms  4  May 23rd, 2012 08:09 AM 
Add to the list if you can  asbo  New Users  0  May 1st, 2010 01:51 AM 