File I/O to linked list

Oct 11, 2011 at 12:30am
Hi everyone!!

Can anyone help me with my problem? I have a assignment to input values to a singly linked list from a file and than output it. But I when I run the program the numerical data from a file does not appear.

Program compiles without any mistake, and i can't understand where is the problem.
Please help me if anyone knows what is the problem there!!!!

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
#include <iostream>
#include <fstream>
using namespace std;

struct Node{
  int data;
  Node *next;
};
typedef Node* NodePtr;

NodePtr addHeadNode(NodePtr head, int NewData); //function inputs the list

void printList(NodePtr head); // function to print it out



int main(){
  
   int a;
  
  ifstream fin;
  ofstream fout;
  
  fin.open("numbers.in");  
  
  while(!fin.eof()){
    fin>> a;
    NodePtr addHeadNode(NodePtr head, int a);
    
  }
  fin.close();
  
  cout<< "SINGLY LINKED LIST: " << endl;
  void printList(NodePtr head); 
  
  
 return 0; 
}

NodePtr addHeadNode(NodePtr head, int NewData){
     
  NodePtr NewPtr = new Node;
  
  NewPtr->data = NewData;
  NewPtr->next = head;
  
  return NewPtr;
}

void printList(NodePtr head){
  NodePtr p;
  p = head;
  
  while(p != NULL){
    cout<< p->data << endl;
    p=p->next;
  }
}
Oct 11, 2011 at 8:59am
honestly speaking, your code is with too many many bugs, here is a compilabe version:

#include <iostream>
#include <fstream>

using namespace std;

struct Node{
int data;
Node *next;
};

typedef Node* NodePtr;

NodePtr& addHeadNode(NodePtr& head, int NewData); //function inputs the list

void printList(NodePtr& head); // function to print it out

int main(){

int a;
ifstream fin;
ofstream fout;
NodePtr head = NULL;

fin.open("numbers.in");

while(fin>>a) addHeadNode(head,a);

fin.close();

cout<< "SINGLY LINKED LIST: " << endl;

printList(head);

return 0;
}

NodePtr& addHeadNode(NodePtr& head, int NewData)
{
NodePtr NewPtr = new Node();
NewPtr->data = NewData;
NewPtr->next = NULL;

NodePtr p = head;

if(p == NULL) head = NewPtr;
else
{
while(p->next != NULL) p = p->next;
p->next = NewPtr;
}

return head;
}

void printList(NodePtr& head)
{
NodePtr p = head;

while(p != NULL)
{
cout<< p->data << endl;
p = p->next;
}
}
Oct 11, 2011 at 5:35pm
Dude you are awesome!!!
It works now!!!!
Many many thanks!!!

By any chance do you know how to copy the content of a singly linked list into a doubly linked list!!!??

And thank you again for your help!!

Oct 11, 2011 at 7:26pm
Stop posting full code solutions! These students are never going to learn anything if you keep doing the work for them!
Nov 12, 2011 at 3:25am
I doubt that!

sometimes complete solutions are fare better easier to understand and to learn from.
Topic archived. No new replies allowed.