Академический Документы
Профессиональный Документы
Культура Документы
Items are removed from a stack in the reverse order from the
way they were inserted
Items are removed from a queue in the same order as they
were inserted
stk: 17
23
97
or count = 4
44
top = 3
After popping
0
9
stk: 17
23
97
44
top = 2
or count = 3
Sharing space
stk:
0
9
44
97
23
17
or count = 4
top = 6
Sometimes this is done to allow two stacks to share the same
storage area
0
9
stks: 49
57
topStk1 = 2
44
97
23
17
topStk2 = 6
5
Error checking
Since all the action happens at the top of a stack, a singlylinked list (SLL) is a fine way to implement it
The header of the list points to the top of the stack
myStack:
44
97
23
17
Unlike an array implementation, it really is removed-you can no longer get to it from the linked list
Hence, garbage collection can occur as appropriate
8
myQueue:
front = 0
0
7
17
23
97
44
rear = 3
front = 0
Initial queue:
17
23
97
44
After insertion:
17
23
97
44 333
23
97
44 333
After deletion:
front = 1
rear = 4
Notice how the array contents crawl to the right as elements are inserted and
deleted
This will be a problem after a while!
10
Circular arrays
myQueue:
0
7
44
rear = 1
55
11
22
33
front = 5
Elements were added to this queue in the order 11, 22, 33,
44, 55, and will be removed in the same order
Use: front = (front + 1) % myQueue.length;
and: rear = (rear + 1) % myQueue.length;
11
myQueue:
0
7
44
55
66
77
88
11
22
rear = 4
33
front = 5
0
7
This is a problem!
rear = 4
front = 5
12
myQueue:
0
7
44
55
66
77
88
11
22
33
count = 8
rear = 4
front = 5
Solution #2: (Slightly more efficient) Keep a gap between
elements: consider the queue full when it has n-1 elements
myQueue:
0
7
44
55
66
77
rear = 3
11
22
33
front = 5
13
If you know where the last node in a list is, its hard
to remove that node, but its easy to add a node
after it
Hence,
15
Enqueueing a node
Node to be
enqueued
last
first
44
97
23
17
Dequeueing a node
last
first
44
97
23
17
Copy the pointer from the first node into the header
17
18