Download presentation
Presentation is loading. Please wait.
Published byEzra Marsh Modified over 7 years ago
1
Advanced Higher Computing Science Stacks Queues and linked lists
Welcome to the 3rd Advanced Higher homework session looking at complex data structures
2
Why do we need data structures?
How we represent data when solving a problem should mirror the real world as closely as possible Data structures should be what you think about when first approaching a problem Your choice can influence the progress of your project. What kind of information do you need to store? What type of data is it? (string, integer, real, Boolean) Does your information have a structure? (single items list, or grid) Does it matter what order your data is stored in How are you going to manipulate it? (search, sort, insert, remove, link)
3
Are all complex data structures arrays?
An array is a set of contiguous blocks of memory. Resizing an array is a complex and memory intensive operation Storing data in non contiguous blocks makes the data structure more flexible but more complex There are low level considerations to data structures
4
Real world examples: Stacks
Browser history Interrupts Blog posts Stack is last in first out
5
Real world examples: Stacks
Undo function To do lists
6
The Stack A stack is a 1-dimensional array or list where data elements can be added or retrieved only from the top of the stack. The terms push and pop refer to adding and removing items respectively. In a stack, a pointer is required to identify the location of the top of the stack A stack is often referred to as a "Last in First Out" structure
7
The stack
8
The interrupt stack: Run programA Interrupt event (interrupt1)
Store programA register contents in memory. Push programA memory location on to stack Run interrupt1 Interrupt event (Interrupt2) Store interrupt1 register contents in memory. Push interrupt 1 memory location on to stack Run interrupt2 Complete Interrupt2 routine Pop interrupt1 memory location from stack Retrieve interrupt1 status and register contents from memory location Complete interrupt1 routine interrupt1 complete Pop programA memory location from stack Retrieve programA status and register contents from memory location Continue programA
9
Implementing a stack stackPointer is used to keep track of the top of the stack max is the maximum number of items which the stack can hold stack[] is an array to hold the data
10
Implementing a stack CLASS Stack IS {INTEGER stackPointer, INTEGER max, INTEGER stack[]} METHODS CONSTRUCTOR Stack(INTEGER size) DECLARE THIS.stack INITIALLY []*size DECLARE THIS.stackPointer INITIALLY 0 DECLARE THIS.size INITIALLY size END CONSTRUCTOR PROCEDURE Push(INTEGER value) IF THIS.stackPointer=THIS.size THEN <stack overflow action> ELSE SET THIS.stack[THIS.stackPointer] TO value SET THIS.stackPointer TO THIS.stackPointer+1 END IF END PROCEDURE The constructor function runs when an object is created from a class. It creates the stack structure of the required size, and sets max to be maximum number of elements the stack can hold (from the size parameter passed as a parameter) The push procedure detect trying to write to a full stack (a stack overflow error) Otherwise, if the stack isn't full we can push the value onto the stack and update the stackPointer to the new top of the stack.
11
Implementing a stack FUNCTION pop() RETURNS INTEGER IF THIS.stackPointer=0 THEN <stack underflow action> ELSE SET THIS.stackPointer TO THIS.stackPointer -1 RETURN THIS.stack[THIS.stackPointer] END IF END FUNCTION END CLASS The pop function detect if is the stack is empty, if it is then it catches the stack underflow error, otherwise if the stack has elements in it then it returns the value and moves the stackPointer to show there is one less item in the stack.
12
Real world examples: Queues
Tech Support helplines Queues are first in first out structures
13
Real world examples: Queues
Scheduled tasks Printer queues
14
The Queue A queue is a 1-dimensional array or list, but data elements are inserted and retrieved at different ends. In a queue two pointers are required: one to point to the head of the queue and one to point to the end. A queue is a "First in First Out" structure. We're going to look at 2 types of queue the circular queue and a queue which mirrors the real world queue you might find when people are waiting in a line. In a circular queue data the pointers move, not the data.
15
The Circular queue
16
The Circular queue When the last space in the array is reached the rear pointer is moved to the start of the array. What would this queue look like after the following operations? Leave 6 Join 77
17
The Circular queue What would this queue look like after the following operations? Leave 6 Join 77
18
Implementing a Circular queue
start is used to keep track of the front of the queue rear is used to keep track of the back of the queue maxSize is the maximum number of items which the queue can hold currentSize is the current number of items which the queue is holding queue[] is an array to hold the data
19
Implementing a circular queue
CLASS Queue IS {INTEGER start, INTEGER rear, INTEGER currentSize, INTEGER maxSize, ARRAY OF INTEGER queue} METHODS CONSTRUCTOR Queue(INTEGER size) DECLARE THIS.start INITIALLY 0; DECLARE THIS.rear INITIALLY 0; DECLARE THIS.currentSize INITIALLY 0 DECLARE THIS.maxSize INITIALLY size; DECLARE THIS.queue INITIALLY INTEGER[maxSize] END CONSTRUCTOR The constructor function runs when an object is created from a class. It creates the queue structure of the required size with start and rear pointers.
20
Implementing a circular queue
PROCEDURE join(INTEGER data) IF THIS.currentSize = THIS.MaxSize THEN SEND "Queue Overflow" TO DISPLAY ELSE SET THIS.queue[THIS.rear] TO data SET THIS.rear TO THIS.rear + 1 SET THIS.currentSize TO THIS.currentSize + 1 END IF IF THIS.rear > THIS.maxSize THEN SET THIS.rear TO 1 END PROCEDURE The join procedure checks to ensure that the queue is not full, otherwise it adds the data passed as a parameter to the rear of the queue and updates the rear pointer and currentSize. If the rear position is greater than maxSize, then the rear pointer is set back to 1.
21
Implementing a circular queue
FUNCTION leave() RETURNS INTEGER IF THIS.currentSize = 0 THEN SEND "Queue Underflow" TO DISPLAY RETURN 0 ELSE RETURN THIS.queue[THIS.start] SET THIS.queue[THIS.start] TO 0 SET THIS.currentSize TO THIS.currentSize - 1 SET THIS.start TO THIS.start + 1 END IF IF THIS.start > THIS.maxSize THEN SET THIS.start TO 1 END FUNCTION END CLASS The leave function checks to ensure that the queue is not empty, otherwise it returns the item at the start position, updates currentSize and the start pointer. If the start position is greater than maxSize, then the start pointer is set back to 1.
22
A queue with one pointer
Why is this inefficient? Join 56 Leave 6
23
A queue with one pointer
queuePointer keeps track of the front of the queue size is the maximum number of items which the queue can hold queue[] is an array to hold the data
24
A queue with one pointer
CLASS Queue IS {ARRAY OF INTEGER queue, INTEGER queuePointer, INTEGER size} METHODS CONSTRUCTOR Queue(INTEGER queueSize) DECLARE THIS. size INITIALLY queueSize DECLARE THIS.queue INITIALLY [size] DECLARE THIS.queuePointer INITIALLY 0 END CONSTRUCTOR
25
A queue with one pointer
PROCEDURE join(INTEGER value) IF THIS.queuePointer=THIS.size THEN <queue overflow action> ELSE SET THIS.queue[THIS.queuePointer] TO value SET THIS.queuePointer TO THIS.queuePointer+1 END IF END PROCEDURE
26
A queue with one pointer
FUNCTION leave() RETURNS INTEGER DECLARE result INITIALLY <whatever> IF THIS.queuePointer=0 THEN <queue underflow action> ELSE SET result TO THIS.queue[0] FOR i FROM 0 TO THIS.queuePointer-2 DO SET THIS.queue[i] TO THIS.queue[i+1] END FOR SET THIS.queuePointer TO THIS.queuePointer-1 END IF RETURN result END FUNCTION END CLASS
27
Real world examples: Linked lists
Road train File blocks on disk Disk OS used bitmap but with increased sizes of disks the bitmap took up too much space Block size is always a compromise between efficiency and disk space
28
Linked Lists A linked list is a dynamic data structure, which means that its size is not fixed Each item in a linked list consists of the data and a link to the memory location of the next item. A linked list is very flexible as the order of items in a linked list can be changed without actually moving any data around, just the links between them.
29
File blocks on disk Why does this data need to be stored as a dynamic structure? What causes disk fragmentation and why is it a problem? What is done during disk defragmentation?
30
Linked Lists it is not possible to identify a specific item directly using its index in the way that you can when storing data in an array. To identify the position of an item in a linked list you have to walk through the list from beginning to end. Linked lists can be used to implement queues and stacks as well as arrays, with the advantage that they do not need to have a fixed size, avoiding overflow errors.
31
Implementing a linked list
32
Implementing a linked list
CLASS LinkedList IS {INTEGER data, POINTER head, POINTER next} # POINTER is a link to a memory location# METHODS CONSTRUCTOR LinkedList DECLARE THIS.data INITIALLY DECLARE THIS.head INITIALLY NUL DECLARE THIS.next INITIALLY NUL END CONSTRUCTOR PROCEDURE setupList() DECLARE THIS.data INTEGER INITIALLY 0 DECLARE THIS.head POINTER INITIALLY NUL END PROCEDURE
33
Implementing a linked list
PROCEDURE newNode(INTEGER data, POINTER next POINTER head) IF THIS.head = NUL THEN <point head to data> THIS.next = NUL ELSE <check each node in turn until the one pointing to NUL is found> <point last node to data> END IF END PROCEDURE
34
Implementing a linked list
PROCEDURE deleteNode(INTEGER data POINTER head) IF THIS.head = NUL THEN SEND "List is empty" TO DISPLAY ELSE IF <head points to data> THEN <point head to next item in list> END IF DECLARE found INITIALLY FALSE REPEAT <loop through items> IF <current item = data> THEN <Point current item to next item in list> SET found TO true UNTIL <current item pointer> = NUL IF found = false THEN SEND "not found" TO DISPLAY END PROCEDURE END CLASS
35
Using a linked list to implement a stack or a queue
Since a linked list is a dynamic structure, a stack can grow and shrink as items are pushed and popped. The stack pointer effectively becomes the last item in the list If a linked list is used to implement a queue, since it is a dynamic structure, the front and back of the queue are the last and first items in the list. Both structures will require a variable to store the maximum number of items allowed in the linked list.
36
Past paper Examples 2016 Q2d, Q 3d Specimen Paper Q 3a
Old Advanced Higher 2014 Q4 Old Advanced Higher b Old Advanced Higher 2010 Q2
37
2016 Q2d The titles of the songs in one of the playlists are exported to a program for processing using a queue structure. The queue has been implemented as a 1-D array. The contents of the queue are shown below: Use pseudocode to write an algorithm to remove a played song from the top of the playlist queue.
38
2016 Q2d IF front = back THEN <queue is empty> ELSE <play playlist[front]> SET front TO front-1 END IF
39
2016 Q3d(i) The names of the top 10 medal winning teams are held in a stack. Part of the stack is shown. The USA wins enough medals to be fourth on the table. Write down the sequence of stack operations required to produce the new table.
40
2016 Q3d(i) Pop Australia, pop France, push USA, push France,
push Australia
41
2016 Q3d(ii) The stack storing the medal winning teams could be implemented using a linked list. The diagram below represents a linked list after the first six teams have been added to the medal table. Team Russia is to be added to the medal table between Germany and the USA. Describe how team Russia would be added to the correct place inthe linked list.
42
2016 Q3d(ii) A new node would be added to store Russia and its pointer would be set to 241 (team Germany). The pointer of the node containing USA would be updated; instead of storing 241, it would now store the address of the new node.
43
Specimen Paper Q 3a A computerised version of a card game, based on various animals native to Scotland, is being developed for a website. During game play, players can take a card from or place a card on a pile of cards. A stack data structure will represent this pile of cards. The stack is held in a 1-D array and the last item placed in the stack was the Golden Eagle. The 1-D array in which the stack is held is shown below:
44
Specimen Paper Q 3a (i) An item is added to the stack by “pushing” and removed by “popping”. Draw the final state of the stack after the following five operations: 1. Pop 2. Push Loch Ness Monster 3. Pop 4. Pop 5. Push Grouse Index Character Ptarmigan 1 Otter 2 Golden Eagle 3 4
45
Specimen Paper Q 3a (i) An item is added to the stack by “pushing” and removed by “popping”. Draw the final state of the stack after the following five operations: 1. Pop 2. Push Loch Ness Monster 3. Pop 4. Pop 5. Push Grouse Index Character Ptarmigan 1 Grouse 2 3 4
46
Specimen Paper Q 3 (ii & iii)
(ii) Apart from the 1-D array, describe another item of data required to implement a stack. A stack pointer (INTEGER) is required to store the index position of the top of the stack (iii) When a stack is implemented using a 1-D array, adding a valid item can cause an execution error. Explain why an execution error can occur in this situation. Stack Overflow occurs when the array is full and an attempt is made to access an index position which does not exist.
47
Specimen Paper Q 3b (i) A linked list could have been used rather than a stack to represent the pile of cards. (i) The animals Ptarmigan, Otter and Golden Eagle are entered, in the order given, into a linked list. Draw this linked list.
48
Specimen Paper Q 3b (i) A linked list could have been used rather than a stack to represent the pile of cards. (i) The animals Ptarmigan, Otter and Golden Eagle are entered, in the order given, into a linked list. Draw this linked list.
49
Specimen Paper Q 3b (ii) (ii) Explain why the execution error in part (a) (iii) would not occur if a linked list is used rather than a stack. A linked list is a dynamic structure (items are not stored contiguously in memory) so the number of items is not fixed and items can be easily added
50
2014 Q4 In the early days of hand-held calculators, ‘Postfix’ notation was used to reduce memory access during a calculation and made use of the stack to evaluate expressions. Postfix notation avoids the use of brackets. The arithmetical expression 6 * (4 + 3) is written in Postfix notation as * and is then processed, left to right, using a stack.
51
2014 Q4
52
2014 Q4 The arithmetical expression 6 * (4 + 3) is written in Postfix notation as * At the beginning of the process the stack is empty. The first element input is a 6 and this is pushed onto the stack. 1 2 3 4 5 6 Stack pointer After the number “4” has been pushed on to the stack, the state of the stack is: 1 2 3 4 5 6 Stack pointer 1 (a) Explain why the “stack pointer” is needed during stack operations.
53
2014 Q4 (b) (i) Following the algorithm above, show the state of the stack after the 3 has been pushed on to the stack. (ii) Show the contents of the stack, and the value of the stack pointer, after the algorithm has run to completion.
54
2014 Q4 (i) Following the algorithm above, show the state of the stack after the 3 has been pushed on to the stack. ii) Show the contents of the stack, and the value of the stack pointer, after the algorithm has run to completion.
55
2014 Q4 (i) Following the algorithm above, show the state of the stack after the 3 has been pushed on to the stack. 1 2 3 4 5 6 Stack pointer 2 ii) Show the contents of the stack, and the value of the stack pointer, after the algorithm has run to completion.
56
2014 Q4 (i) Following the algorithm above, show the state of the stack after the 3 has been pushed on to the stack. 1 2 3 4 5 6 Stack pointer 2 ii) Show the contents of the stack, and the value of the stack pointer, after the algorithm has run to completion. 1 2 3 4 5 6 7 Stack pointer 1
57
2014 Q4 (i) Following the algorithm above, show the state of the stack after the 3 has been pushed on to the stack. 1 2 3 4 5 6 Stack pointer 2 ii) Show the contents of the stack, and the value of the stack pointer, after the algorithm has run to completion. Strictly speaking, when the stack pointer moves back, the data in positions 1 and 2 does not need to be deleted, since the pointer determines the top of the stack. An analogous situation would be what happens when you delete a file on disk – the blocks don’t get emptied, just marked as empty so that they can be subsequently written over - this is why undelete programs can retrieve data from deleted files. 1 2 3 4 5 6 7 Stack pointer 1 1 2 3 4 5 6 42 Stack pointer
58
2014 Q4 (c) The algorithm above makes use of the “pop” operation. Use pseudocode to describe the operation to pop a value from the stack. (d) Describe one problem that should be checked for when pushing a value onto a stack.
59
2014 Q4 c) IF <stack is empty> THEN SEND "Stack underflow" TO DISPLAY ELSE SET outputValue TO stack[stackPointer] SEND outputValue TO DISPLAY SET stackPointer TO stackPointer -1 END IF d) Stack overflow
60
2012 4b A 1-D array with six elements is used to hold the contents of a queue and the variables front and rear are used to hold the positions of the item at the front and rear of the queue. The following lines of code are executed: MyQ.addtoback(15) MyQ.addtoback(29) MyQ.remove MyQ.addtoback(8) The following diagram shows that 29 and 8 are in the queue. The number 15 is still present in the 1-D array but is not in the queue. Index 1 2 3 4 5 15 29 8 front 1 rear 2
61
2012 4b State what happens to the variables front and rear when a number is removed from the queue. SET front TO front + 1 ii) The state of MyQ shown above is changed by executing these additional lines of code: MyQ.addtoback(11) MyQ.remove MyQ.addtoback(9) Draw a diagram that shows the new state of MyQ Index 1 2 3 4 5 15 29 8 11 9
62
2012 4c (i) Describe the problem that will arise as items continue to be added and removed from MyQ. The end of the array will be reached but there is still room in the array for items to be placed in the queue (ii) Describe how the problem in (c)(i) could be solved. Either use a circular queue where items joining the queue will be added to the start of the array and the pointer rear will become 1 Or Reset the array every time an item is removed by shuffling items one place up
63
2010 Q2
64
2010 Q2 Explain why the characters L, E and D have not been moved to the locations identified by indices 0, 1 and 2 after characters C and A have been processed. It would be very inefficient to move every character one place up every time a key is pressed (b) State the values stored in the variables front and rear after the characters O and N have been added and a further three characters removed from the queue. Front = 5 Back = 6
65
2010 Q2c (c) Characters will continue to be added and removed from the queue held in the 1-D array. State the problem encountered as characters continue to be added and removed. Rear will reach 9 but the queue is not full as there are spaces at the front of the array. (ii) Describe how to solve the problem encountered in (i). The solution would be to wraparound where items are added at the start of the array.
66
2010 Q2d Another data structure used in programming is a stack.
Explain how the operation of a stack data structure differs from a queue. In a stack items are popped and pushed at the same end. In a queue items leave at one end and join at the other (ii) Explain why a keyboard buffer does not use a stack data structure. Characters would be processed in the wrong order ( last key pressed processed before earlier characters )
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.