Linked Lists, Queues, and Stacks Linked Lists: 5 3 8 Head
Linked Lists, Queues, and Stacks Linked Lists: 5 3 8 Head
2. Destroy list
head 3 5 8
3. Retrieve value at specified position
{ void initializeList()
int value;
{
listNode *next;
head = NULL;
};
numItems = 0;
}
static listNode *head; /* points to first list item */
Locating The
Inserting Values
Insertion Point
Two steps:
If the list is sorted, this requires a loop
Locate insertion point
We want a pointer to the node BEFORE the
Insert new list element
insertion point
Step two requires some care!
Inserting The
Order Matters!
New Element
insPt insPt
insPt->next is our only
insPt points to the
reference to the rest
node BEFORE the
insertion point 3 5 of the list 3 5
If we change that
newEl points to the
first, we lose the rest
new list element
newEl 4 of the list! newEl 4
Algorithm: First Try Algorithm: Second Try
insPt insPt
newEl 4 2 newEl 4
Finding The
Pointers for Removal
Removal Point
Doubly-linked list
first-in, first-out (FIFO) data structure
Each node also contains a pointer to the
Real-world examples:
preceding list node
grocery checkout, on/off-ramp
Circular linked lists
Programming examples
Last node points to first node, not NULL
print jobs, processes running on a CPU
One pointer (to the tail) stores entire list
1. Create queue
(as opposed to circular queues)
2. Destroy queue
Maintain two pointers
3. Enqueue (insert element at tail)
one to head of queue (for removal)
4. Dequeue (remove element at head)
one to tail of queue (for insertion)
5. Get number of elements
Special case: empty queue Special case: only one element in queue
set head and tail to point to new element set tail to point to NULL
Otherwise: Otherwise:
Array-Based
Stack Deletion (Pop)
Implementations
Just as easy as insertion
Stacks and queues are also easy to
implement using arrays