Linked list
Aug 23, 2014 at 12:08am UTC
I made this programme that adds some numbers to the list and then shows
but i m not getting this to work .... input part goes right but when it comes to
displaying the linked list it throws exception.... plz help me .....
thanks in advance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
using namespace std;
struct list{
int data;
list* link;
};
ostream& operator <<(ostream& os,const list &l){
return os << "Data : " << l.data;
}
list* enterData(){
list *head, *newNode, *last;
head = NULL;
last = NULL;
int num;
cout << "\t\t\tEnter numbers in list\n\n" ;
cin >> num;
while (num != -1)
{
if (!cin)
throw "input stream failure" ;
try {
newNode = new list;
newNode->data = num;
newNode->link = NULL;
if (head == NULL)
{
head = newNode;
last = newNode;
}
else
{
last->link = new list;
last = new list;
}
}
catch (bad_alloc b)
{
cout << b.what();
}
cout << "\t\t\tEnter numbers in list\n\n" ;
cin >> num;
}
return head;
}
void showData(list* head){
list *newNode;
//head = new list;
newNode = head;
while (newNode != NULL)
{
cout << "The data in list is " << *newNode << endl;
newNode = newNode->link;
}
}
int main(int argc, char * argv[])
{
list*head = enterData();
cout << "Showing data in the list\n\n" ;
Sleep(3000);
showData(head);
return 0;
}
Aug 23, 2014 at 2:05am UTC
Your else case on line 42-43 is wrong. You already created a new node and populated it with data above. Your else case should simply be
1 2
last->link = newNode;
last = newNode;
Aug 24, 2014 at 6:17pm UTC
Thanks bro i realized the problem and it's now working .... so foolish of me
Topic archived. No new replies allowed.