new Node in LinkLists

I have three related questions.

I have a node class and a Linklist class defined as below.
1)
The setNext() function of node class, takes pointer to a Node as argument
1
2
3
4
5
 
void Node::setNext(Node * ptr)
{
    next = ptr;
}


nut when i pass it a 'nullptr', i don't get any errors and everthing works just fine.
 
n->setNext(nullptr);

How does this happen? Is it 'safe' or is it a bad practice. I really need to set it to null in some cases(last node of link list) while in others it should point to its next node in the link list.

2)
In function
 
void LinkList::AddToEnd(int s)

i create a new node with a pointer. What would be logically wrong with not creating a pointer to a node and just creating a node itself. I mean instead of
 
 Node * n = new Node();


if I only do
1
2
 
Node n;


I know the parameters in setters and getter function would be needed tan update and also some other places but my question is why is a link list always created with a pointer? is it to make sure its always dynamic and gets memory from heap?
Just creating a node object without a pointer would also get its memory from heap? or somewhere else?

3)
In case of new node pointer creation in function

 
void LinkList::AddToEnd(int s)


where do i delete it? deleting it at the end of this function gives garbage vales in print. should i delete it at the end of main? what happens to new node pointer scope at the end of this function?


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
  class Node
{
private:
    int data;
    Node * next;

public:
    Node();
    void setData(int);
    int getData();
    void setNext(Node *);
    Node * getNext();

};


class LinkList
{
private:
    Node * head;

public:
    LinkList();
    void AddToEnd(int);
    Node * getLastNode();
    void Print();

};

void LinkList::AddToEnd(int s)
{
    Node * n = new Node();
    n->setData(s);
    n->setNext(nullptr);///ASK

    if(head == nullptr)
    {
        head = n;
    }
    else if (head != nullptr)
    {
        Node * last = getLastNode();
        last->setNext(n);
    }
  //  delete n;
}
Last edited on
1) no problem. But you should set next to nullptr in the constructor.

2)
if I only do
n is a local variable and will be destroyed when the function AddToEnd(...) id done.

3)
where do i delete it?
In the destructor. If you further delete head in the destructor of LinkList everything will be cleanly destructed.
Topic archived. No new replies allowed.