append node to list

Please help me find out the error in this code
Thank you
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
#include <iostream>

using namespace std;

class Node
{
      public:
             int data;
             Node *next;
};

class List
{
      private:
             Node* head;
      public:
             List() {head=NULL;}
             void appendNode (int);
             /*void sort();*/
             void display(void);
             /*void merge(List &, List&);*/
};

void List::appendNode(int num)
{
     Node* newnode;
     Node* nodeptr;
     newnode->data = num;
     newnode->next = NULL;
     
     if(head=NULL)
     {
          head = newnode;
     }
     else
     {
          nodeptr = head;
          while(nodeptr->next!=NULL)
          {
               nodeptr = nodeptr->next;
          }
          nodeptr->next = new Node();
          nodeptr->next->data = num;
     }
}

void List::display()
{
     int count = 0;
     Node* currNode = head;
     while (currNode!=NULL)
     {
           cout << currNode->data << " ";
           currNode = currNode->next;
           count++;
     }
     cout << "\nNumber of nodes in the list: " << count << endl;
}

int main()
{
    List list1;
    list1.appendNode(9);
    list1.appendNode(4);
    list1.appendNode(3);
    list1.appendNode(12);
    list1.appendNode(100);
    list1.display();
    
    getchar();
    return 0;
}
     
             
Which errors you get?

two things I've seen:

- in appendNode Node* newnode;-> newnode is just setted and never used (it's not an error but you
can erase it)

- I'm not sure but I think for nodeptr->next = new Node(); you need a constructor and later a destructor in public part of Node class
Last edited on
- In void List::appendNode(int num) method, you need to allocate memory for the new node, even for the first one (head) :

Node* newnode = new Node(); instead of Node* newnode;

- Then, you have a classical test error (assignment instead of equality test) :
if(head=NULL) should be if(head==NULL)

- And finally, you can use the previously created/allocated newnode variable :
nodeptr->next = newnode; instead of nodeptr->next = new Node();

You can comment //nodeptr->next->data = num; . It's no use then ... You previously set data for newnode.
thank, it worked
Topic archived. No new replies allowed.