Lecture 19 - Oct 19, 2023
Summary
In this lecture, we discuss queues, and start discussing ordered linked lists.
Last lecture
Stacks.
Today
Queues and general linked lists.
Recap on queues
Two operations: enqueue
and dequeue
.
Putting a node or removing a node happens with FIFO (first-in-first-out).
dequeue()
: Removes the node that was first put in a list.
enqueue()
: Puts a node at the end of the list.
Class implementation of a Queue
class Queue {
private:
* head;
Node
// point to end of the queue to facilitate dequeue of nodes
* tail;
Node
public:
() {
Queue= NULL;
head = NULL;
tail }
~Queue() {
// enough to free up all nodes in linked list
delete head;
}
void enqueue(int d) {
* p = new Node(d, NULL);
Node->setNext(p);
tail=p;
tailif (head == NULL) {
= p;
head }
}
int dequeue() {
if (head == NULL) {
return -1;
}
* p = head;
Node= p->getNext();
head int d = p->getData();
->setNext(NULL); // very important
pdelete p;
return d;
}
};
;
Queue q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q
// output 123
<< q.dequeue() << q.dequeue() << endl; cout
Recall the diagram from lecture 18.
Ordered linked lists
Four basic operations
- Insert in sorted order
- Search
- Delete
- 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
// 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)
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() > c 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.
Next lecture: delete data, “copy” constructor, operator=
.