Linked List

Singly Linked List
Each node contains the data it’s holding and a pointer to its next element.

#include "SinglyLinkedList.h"

using namespace std;

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

void SinglyLinkedList::add(Person newPerson)
{
	Node *newNode = new Node;
	newNode->person = newPerson;
	newNode->next = NULL;

	if (head == NULL) {
		head = newNode;
	}
	else{
		Node *cur = head;
		while (cur->next != NULL) {
			cur = cur->next;
		}
		cur->next = newNode;
	}
}

void SinglyLinkedList::remove(Person targetPerson)
{
	if (head == NULL) {
		return;
	}

	if (head->person == targetPerson) {
		Node *tmp = head;
		head = head->next;
		delete tmp;
		tmp = NULL;
	}
	else {
		Node *prev = head;
		Node *cur = head->next;
		while (cur->person != targetPerson) {
			if (cur == NULL) {
				return;
			}
			prev = cur;
			cur = cur->next;
		}
		prev->next = cur->next;
		delete cur;
		cur = NULL;
	}
}

void SinglyLinkedList::print()
{
	Node *cur = head;
	while (cur != NULL) {
		cout << cur->person << " -> ";
		cur = cur->next;
	}
	cout << "NULL" << endl;
}

SinglyLinkedList::~SinglyLinkedList()
{
	Node *cur = head;
	while (cur != NULL) {
		Node *tmp = cur;
		cur = cur->next;
		delete tmp;
		tmp = NULL;
	}
}

 

Doubly Linked List
Nodes contain pointers to the previous item as well as the next item.

Advertisements