Lecture 20 - Oct 20, 2023
Summary
In this lecture, we continue our discussion on ordered linked lists. We discuss operations like searching, inserting, deleting nodes in a linked list.
Last lecture
Queues and introduced ordered linked lists.
Today
Search, insert, delete.
Recap on ordered lik
Four basic operations: insert in sorted order, search delete, and copy.
In List.h
:
#include "Node.h"
class List {
private:
* head;
Node
public:
() { head = NULL; }
List~List() { delete head; }
void insertData(int d);
bool dataExists(int d);
bool deleteData(int d);
(const List&); // copy constructor
List& operator=(const List&);
List};
Search linked list
bool dataExists(int d) {
* p = head;
Node
// the 2nd condition is because, otherwise, d won't be after that if
// the linked list is sorted
while (p != NULL && p->getData() < d) {
if (p->getData() == d) {
return true;
} else {
= p->getNext();
p }
}
return false;
}
Insert into list (general case)
Recall the diagram from lecture 19.
Search for the first node with data greater than the data we want to insert.
Insert the new data before that node.
// d = 3
bool List::insertData(int d) {
* n = new Node(d);
Node* p = head, *prev = NULL;
Node
// list is empty
if(p == NULL) {
= n;
head }
while(p != NULL && p_>getData() < d) {
= p;
prev = p->getNext();
p }
// either p->getData < d or p == NULL
->setNext(p); // case 1
n
if(prev == NULL) {
= n; // case 2
head } else {
->setNext(n); // case 3
prev}
}
Cases 1, 2, 3 are shown in the diagram below.
Special cases:
- If list is empty.
- If list has one node.
- If we insert at head.
- If we insert at tail.
Delete data (general case)
bool List::deleteData(int d) {
* p = head, *prev = NULL;
Node
while(p != NULL && p->getData() < d) {
if(p->getData() == d) {
return false;
} else {
= p;
prev = p->getNext();
p }
}
// p is NULL or p->getData() == d
if(p == NULL) {
return false; // not found
}
// delete at front
if(prev == NULL) {
= p->getNext();
head } else {
// delete at middle or tail
->setNext(p->getNext());
prev}
// delete p
->setNext(NULL);
pdelete p;
}
Destructor
::~List() {
Listdelete head;
}
Copy constructor
The copy constructor creates an object from an existing one.
The default copy constructor does a shallow copy.
We need to do a deep copy:
- Copy one node at a time.
p
to iterate original list,np
to build new list.
::List(const List& original) {
List*p = original.head;
Node *np = NULL;
Node = NULL;
head
while (p != NULL) {
*n = new Node(p->getData(), NULL);
Node if (np == NULL) {
= n;
head } else {
->setNext(n);
np}
= p->getNext();
p = n;
np }
}