linked lists help

could someone please explain the second part of the if statement in my code? i've been doing an assignment using lecturer notes and stuff i found online (we have to create a list of doubles and code our own functions), i get the general gist of what's going on, but a few comments in plain english would be handy (like i've done for myself in the first part of the if statement). thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef ListOfDoubles_H
#define ListOfDoubles_H

class ListOfDoubles
{
private:
	struct node
	{
		double data;
		node *next;//pointer to next node
	}
	*head;//first node in list
public:
	ListOfDoubles();
	void insert(double number);
	void display();
	double deleteMostRecent();
	int count();
};
#endif; 


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
#include "ListOfDoubles.h"
#include<iostream>
using namespace std;

ListOfDoubles::ListOfDoubles()
{
	head = NULL;
}

void ListOfDoubles::insert(double num)
{
	node *tempNode, *newNode;
	if(head == NULL)//if there's no nodes
	{
		newNode = new node;//create new node
		newNode->data = num;//store data in it
		newNode->next = NULL;//because it's first in list and there's no other nodes, it's not pointing to a node
	}
	else//if there are nodes in the list
	{
		tempNode = head;
		while(tempNode->next != NULL)
		{
			tempNode = tempNode->next;
		}
		newNode = new node;
		newNode->data = num;
		newNode->next = NULL;
		tempNode->next = newNode;
	}
}
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
#include "ListOfDoubles.h"  // declaration of class ListOfDoubles
#include<iostream>  // don't need this
using namespace std; // don't need this

ListOfDoubles::ListOfDoubles()  // Constructor: initialises class members
{
	head = NULL;  // head is initially null indicating empty list
}

void ListOfDoubles::insert(double num)  // insert a double at the end of the list
{
	node *tempNode, *newNode;
	if(head == NULL)  // if we have an empty list
	{
		newNode = new node;  // allocate a new node off the heap
		newNode->data = num;  // fill in the node payload
		newNode->next = NULL;  // initialise the next pointer to null always.
	}
	else
	{
                // use tempNode to walk to the end of the linked list
                // as that's where we'll insert the new node
		tempNode = head;
		while(tempNode->next != NULL)
		{
			tempNode = tempNode->next;
		}
		newNode = new node;;  // allocate a new node off the heap
		newNode->data = num;  // fill in the node payload
		newNode->next = NULL;  // initialise the next pointer to null always.
		tempNode->next = newNode;  // place the new node at the end of the list
	}
}
Last edited on
thanks much appreciated
Topic archived. No new replies allowed.