Linked List: Inserting Value at the End

I've written as follows:

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
#include <bits/stdc++.h>

using namespace std;

struct Node
{
    int Data;
    Node* Next;
};

Node* Head;

void InsertEnd(int num)
{
    Node *NewNode;
    NewNode=new Node;
    NewNode->Data=num;
    NewNode->Next=NULL;

    Node* EndNode;
    EndNode=Head;

    if(EndNode == NULL)
       EndNode=NewNode;
    else
    {
        while(EndNode->Next!=NULL)
            EndNode=EndNode->Next;
        EndNode=NewNode;

    }
}

void PrintList()
{
	Node* NewNode=Head;
	cout<<"List is: ";
	while(NewNode!=NULL)
	{
		cout<<NewNode->Data<<" ";
		NewNode=NewNode->Next;
	}
	cout<<endl;
}

int main()
{
    Head=NULL;
    InsertEnd(90);
    InsertEnd(80);
    PrintList();

    return 0;
}


It doesn't work. Where is the problem?
First of all what does this include do?

#include <bits/stdc++.h>

As how the code is now, seems that do nothing.

This include instead

#include <iostream>

is missing and you need it if you want to use the cout.

Then after this, you do not change Head, that in this way is always init to NULL (btw use nullptr instead of NULL).
Last edited on
closed account (SECMoG1T)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void InsertEnd(int num)
{
    Node *NewNode;
    NewNode=new Node;
    NewNode->Data=num;
    NewNode->Next=NULL;

    Node* EndNode;
    EndNode=Head;

    if(EndNode == NULL)
       EndNode=NewNode;
    else
    {
        while(EndNode->Next!=NULL)
            EndNode=EndNode->Next;
        ///by now EndNode->Next is equal to null
        EndNode->next=NewNode;///so this is what you need

    }
}
Topic archived. No new replies allowed.