Systems Programming Linked lists, stacks and queues Julio Villena - - PowerPoint PPT Presentation

systems programming
SMART_READER_LITE
LIVE PREVIEW

Systems Programming Linked lists, stacks and queues Julio Villena - - PowerPoint PPT Presentation

Systems Programming Linked lists, stacks and queues Julio Villena Romn (L ECTURER ) <jvillena@it.uc3m.es> C ONTENTS ARE MOSTLY BASED ON THE WORK BY : Carlos Delgado Kloos and Jess Arias Fisteus Systems Programming Linked lists Julio


slide-1
SLIDE 1

Linked lists, stacks and queues

Systems Programming

Julio Villena Román (LECTURER)

<jvillena@it.uc3m.es>

CONTENTS ARE MOSTLY BASED ON THE WORK BY:

Carlos Delgado Kloos and Jesús Arias Fisteus

slide-2
SLIDE 2

Linked lists

Systems Programming

1

Julio Villena Román (LECTURER)

<jvillena@it.uc3m.es>

CONTENTS ARE MOSTLY BASED ON THE WORK BY:

Carlos Delgado Kloos and Jesús Arias Fisteus

slide-3
SLIDE 3

Data Structures

  • Abstraction that represents a collection
  • f data in a program in order to ease its

manipulation

  • The suitability of a data structure

depends on the nature of the data to be stored and how that data will be manipulated

2

slide-4
SLIDE 4

Linear Data Structures

  • Organize data as a sequence, where

each piece of data has a preceding datum (except the first one) and a succeeding datum (except the last one)

  • Examples of linear data structures:

– Arrays – Linked lists – Stacks – Queues – Doubly ended queues

3

slide-5
SLIDE 5

Arrays

  • Arrays have two main advantages for

storing linear data collections:

– Random access: any position in the array can be accessed in constant time – Efficient use of memory when all the positions of the array are in use, because the array is stored in consecutive memory positions

4

slide-6
SLIDE 6

Arrays

  • Disadvantages (I):

– Static size: a size must be established when the array is created, and cannot be changed

  • later. The main problems it poses are:
  • Inefficient use of memory when more positions than

needed are reserved, because of being the array sized for the worst case

  • It may happen at run-time that more positions than

reserved are needed

– Need of contiguous memory:

  • Even having the system enough free memory, it

may happen that there is not enough contiguous space, due to memory fragmentation

5

slide-7
SLIDE 7

Arrays

  • Disadvantages (II):

– Some operations on the array have a sub-optimum cost:

  • Insertions and removals of data in the first

position or intermediate positions need data to be moved to consecutive memory positions

  • Concatenation of arrays: data has to be copied

to a new array

  • Partition of an array in several pieces: data

needs to be copied to new arrays

6

slide-8
SLIDE 8

Linked Lists

  • Ordered sequence of nodes in which

each node stores:

– A piece of data – A reference pointing to the next node

  • Nodes do not need to be in

consecutive memory positions

first info next info next info next null 7

slide-9
SLIDE 9

The Node Class

public class Node { private Object info; private Node next; public Node(Object info) {…} public Node getNext() {…} public void setNext(Node next) {…} public Object getInfo() {…} public void setInfo(Object info) {…} }

8

slide-10
SLIDE 10

The Node Class (Generic types)

public class Node<T> { private T info; private Node<T> next; public Node(T info) {…} public Node<T> getNext() {…} public void setNext(Node<T> next) {…} public T getInfo() {…} public void setInfo(T info) {…} }

9

slide-11
SLIDE 11

Inserting a node at the beginning

first null newNode Node newNode = new Node(info); null

10

slide-12
SLIDE 12

Inserting a node at the beginning

newNode newNode.setNext(first); null first

11

slide-13
SLIDE 13

Inserting a node at the beginning

newNode first = newNode; null first

12

slide-14
SLIDE 14

Removing the first node

null first

13

slide-15
SLIDE 15

Removing the first node

data Object data = first.getInfo(); (T) null first

14

slide-16
SLIDE 16

Removing the first node

first data first = first.getNext(); null

15

slide-17
SLIDE 17

Removing the first node

first data null

16

slide-18
SLIDE 18

Inserting a node at an intermediate position

first null newNode Node newNode = new Node(info); previous null

17

slide-19
SLIDE 19

Inserting a node at an intermediate position

first newNode newNode.setNext(previous.getNext()) previous null

18

slide-20
SLIDE 20

Inserting a node at an intermediate position

first newNode previous.setNext(newNode) previous null

19

slide-21
SLIDE 21

Removing an intermediate node

first null previous

20

slide-22
SLIDE 22

Removing an intermediate node

first null previous Object data = previous.getNext().getInfo(); (T) data

21

slide-23
SLIDE 23

Removing an intermediate node

first null previous previous.setNext(previous.getNext().getNext()) data

22

slide-24
SLIDE 24

Removing an intermediate node

first null previous data

23

slide-25
SLIDE 25

Traversing the linked list

first null current Node current = first; while (current != null) current = current.getNext();

24

slide-26
SLIDE 26

Traversing the list: looking for the last node

  • A reference steps the list until a node is

reached whose reference to the next node is null:

public Node searchLastNode() { Node last = null; Node current = first; if (current != null) { while (current.getNext() != null) current = current.getNext(); last = current; } return last; }

25

slide-27
SLIDE 27

Traversing the list: looking for a piece of data

  • A reference steps the list until the piece of

information is reached. A counter is used in order to return its position in the list:

public int search(Object info) { int pos = 1; Node current = first; while (current != null && !current.getInfo().equals(info)) { pos += 1; current = current.getNext(); } if (current != null) return pos; else return -1; }

26

slide-28
SLIDE 28

Advantages of Linked Lists

  • Inserting and extracting nodes have a

cost that does not depend on the size of the list

  • Concatenation and partition of lists have a

cost that does not depend on the size of the list

  • There is no need for contiguous memory
  • Memory actually in use at a given instant

depends only on the number of data items stored in the list at that instant

27

slide-29
SLIDE 29

Disadvantages of Linked Lists

  • Accessing to arbitrary intermediate

positions has a cost that depends on the size of the list

  • Each node represents an overhead in

memory usage

28

slide-30
SLIDE 30

Stacks

Systems Programming

29

Julio Villena Román (LECTURER)

<jvillena@it.uc3m.es>

CONTENTS ARE MOSTLY BASED ON THE WORK BY:

Carlos Delgado Kloos

slide-31
SLIDE 31

Example

30

slide-32
SLIDE 32

Example

31

slide-33
SLIDE 33

Example

32

slide-34
SLIDE 34

Features

  • Linear structure
  • Access on one end both for insertion

and extraction

33

slide-35
SLIDE 35

Main methods

  • Insert on one end:

push(x)

  • Extract at the same end:

pop()

34

slide-36
SLIDE 36
  • Good:
  • ()
  • (()(()))
  • Bad:
  • )(
  • (()
  • ())
  • Rules:
  • Basic: open + close
  • Sequentiation: ()()
  • Nesting: (())

Example: Check brackets

35

slide-37
SLIDE 37

Example: Check brackets

  • Rules:

– Each time we find a “(“ we will put it in the stack – Each time we find a “)” we will extract the upper “(“ of the stack – The string of parentheses is correct if the stack is empty after having gone through to complete string

36

slide-38
SLIDE 38

(()(()())()) Example: check (()(()())())

37

slide-39
SLIDE 39

(()(()())()) ( Example: check (()(()())())

38

slide-40
SLIDE 40

(()(()())()) ( ( Example: check (()(()())())

39

slide-41
SLIDE 41

(()(()())()) ( Example: check (()(()())())

40

slide-42
SLIDE 42

(()(()())()) ( ( Example: check (()(()())())

41

slide-43
SLIDE 43

(()(()())()) ( ( ( Example: check (()(()())())

42

slide-44
SLIDE 44

(()(()())()) ( ( Example: check (()(()())())

43

slide-45
SLIDE 45

(()(()())()) ( ( ( Example: check (()(()())())

44

slide-46
SLIDE 46

(()(()())()) ( ( Example: check (()(()())())

45

slide-47
SLIDE 47

(()(()())()) ( Example: check (()(()())())

46

slide-48
SLIDE 48

(()(()())()) ( ( Example: check (()(()())())

47

slide-49
SLIDE 49

(()(()())()) ( Example: check (()(()())())

48

slide-50
SLIDE 50

(()(()())())

Correct: We have completed the string and the stack is empty

Example: check (()(()())())

49

slide-51
SLIDE 51

([]{()<>}())

Correct: We have completed the string and the stack is empty

Example: check ([]{()<>}())

50

slide-52
SLIDE 52

Example: HTML

<b><i>hello</b></i> – ([)] – Correct with HTML 1.0-4.0 – Incorrect with XHTML <b><i>hello</i></b> – ([]) – Correct with HTML 1.0-4.0 – Correct with XHTML

51

slide-53
SLIDE 53

public interface Stack { public void push(Object o) throws StackOverflowException; public Object pop() throws EmptyStackException; public Object top() throws EmptyStackException; public int size(); public boolean isEmpty(); }

Stack interface

52

slide-54
SLIDE 54

public interface Stack<T> { public void push(T o) throws StackOverflowException; public T pop() throws EmptyStackException; public T top() throws EmptyStackException; public int size(); public boolean isEmpty(); }

Stack interface (Generic types)

53

slide-55
SLIDE 55

ArrayStack Stack LinkedStack

One interface and several implementations

54

slide-56
SLIDE 56

data

1 2 N-1 3 4 5

1 top 2 top 3 top 4 top 5 top top

Array-based implementation

55

slide-57
SLIDE 57

public class ArrayStack<T> implements Stack<T> { public static final int DEFAULT_CAPACITY = 1000; private int capacity; private T data[]; private int top = -1; public ArrayStack() { this(DEFAULT_CAPACITY); } public ArrayStack(int capacity) { this.capacity = capacity; data = new T[capacity]; } …

Array-based implementation

56

slide-58
SLIDE 58

… public int size() { return (top + 1); } public boolean isEmpty() { return (top < 0); } public T top() throws EmptyStackException { if (isEmpty()) throw new EmptyStackException("empty"); return data[top]; } …

Array-based implementation

57

slide-59
SLIDE 59

… public void push(T o) throws StackOverflowException { if (size == capacity) throw new StackOverflowException(); data[++top] = o; } …

Array-based implementation

58

slide-60
SLIDE 60

… public T pop() throws StackEmptyException { T o; if (top == -1) throw new EmptyStackException();

  • = data[top];

data[top--] = null; return o; } }

Array-based implementation

59

slide-61
SLIDE 61

Implementation based on linked lists

Madrid Miami Munich

top

60

slide-62
SLIDE 62

public class Node<T> { private T info; private Node<T> next; public Node(T info, Node next) { this.info = info; this.next = next; } void setInfo(T info) {this.info = info;} void setNext(Node<T> next) {this.next = next;} T getInfo() {return info;} Node<T> getNext() {return next;} }

Implementation based on linked lists

61

slide-63
SLIDE 63

public class LinkedStack<T> implements Stack<T> { private Node<T> top; private int size; public LinkedStack() { top = null; size = 0; } …

Implementation based on linked lists

62

slide-64
SLIDE 64

… public int size() { return size; } public boolean isEmpty() { return (top == null); } public T top() throws EmptyStackException { if (top == null) throw new EmptyStackException(); return top.getInfo(); } …

Implementation based on linked lists

63

slide-65
SLIDE 65

Insertion (push)

Moscow Madrid Miami Munich

top

64

slide-66
SLIDE 66

… public void push(T info) { Node<T> n = new Node<T>(info, top); top = n; size++; } …

Implementation based on linked lists

65

slide-67
SLIDE 67

Extraction (pop)

Madrid Miami Munich Moscow

top

66

slide-68
SLIDE 68

… public T pop() throws EmptyStackException { T o; if (isEmpty()) throw new EmptyStackException();

  • = top.getInfo();

top = top.getNext(); size--; return o; } }

Implementation based on linked lists

67

slide-69
SLIDE 69

Queues

Systems Programming

68

Julio Villena Román (LECTURER)

<jvillena@it.uc3m.es>

CONTENTS ARE MOSTLY BASED ON THE WORK BY:

Carlos Delgado Kloos

slide-70
SLIDE 70

Example

  • The queue at the bus stop
  • The printer queue

69

slide-71
SLIDE 71

Characteristics

  • Linear structure
  • Access on one end for insertion and
  • n the other for extraction

70

slide-72
SLIDE 72

Queue interface

public interface Queue<T> { public int size(); public boolean isEmpty(); public void enqueue(T o) throws QueueOverflowException; public T dequeue() throws EmptyQueueException; public T front() throws EmptyQueueException; }

71

slide-73
SLIDE 73

One interface and several implementations

ArrayQueue Queue LinkedQueue

72

slide-74
SLIDE 74

Array-based implementation

1 2 N-1 3 4 5

1 2 3 4 5

1 2 N-1 3 4 5

5 6 7 8 9 top tail top tail

73

slide-75
SLIDE 75

Implementation based on linked lists

Madrid Miami Munich

top tail

74

slide-76
SLIDE 76

cdk@it.uc3m.es

Implementation based on linked lists

Java: Queues / 75

public class LinkedQueue<T> implements Queue<T> { private Node<T> top = null; private Node<T> tail = null; private int size = 0; … }

75

slide-77
SLIDE 77

Insertion (enqueue)

Moscow Madrid Miami Munich

top tail n

76

slide-78
SLIDE 78

Implementation based on linked lists

public void enqueue(T info) { Node<T> n = new Node<T>(info, null); if (top == null) top = n; else tail.setNext(n); tail = n; size++; }

77

slide-79
SLIDE 79

Extraction (dequeue)

Moscow Madrid Miami Munich

top tail

78

slide-80
SLIDE 80

Implementation based on linked lists

public T dequeue() throws EmptyQueueException { T o; if (top == null) throw new EmptyQueueException();

  • = top.getInfo();

top = top.getNext(); if (top == null) tail = null; size--; return o; }

79

slide-81
SLIDE 81

Activity

  • View queue animations:

http://courses.cs.vt.edu/csonline/DataStructures/L essons/QueuesImplementationView/applet.html

80

slide-82
SLIDE 82

Activity

  • Try the applet DepthBreadth.java

that can be found here:

http://www.faqs.org/docs/javap/c11/s3.html

81

slide-83
SLIDE 83

cdk@it.uc3m.es

Other kinds of queues (not queues any more)

  • Double-ended queues
  • Priority queues

82

slide-84
SLIDE 84

Deques (Double-ended queues)

insertFirst removeFirst removeLast insertLast first last

83

slide-85
SLIDE 85

Interface for deques

public interface Deque<T> { public int size(); public boolean isEmpty(); public void insertFirst(T info); public void insertLast(T info); public T removeFirst() throws EmptyDequeException; public T removeLast() throws EmptyDequeException; public T first() throws EmptyDequeException; public T last() throws EmptyDequeException; }

84

slide-86
SLIDE 86

Stacks and queues as deques

Stack Deque

size() size() isEmpty() isEmpty() top() last() push(o) insertLast(o) pop() removeLast()

Queue Deque

size() size() isEmpty() isEmpty() front() first() enqueue(o) insertLast(o) dequeue() removeFirst()

85

slide-87
SLIDE 87

Definition of stacks from deques

public class DequeStack<T> implements Stack<T> { private Deque<T> deque; public DequeStack() { deque = new Deque<T>(); } public int size() { return deque.size(); } public boolean isEmpty() { return deque.isEmpty(); }

86

slide-88
SLIDE 88

Definition of stacks from deques

public void push(T info) { deque.insertLast(info); } public T pop() throws EmptyStackException { try { return deque.removeLast(); } catch (EmptyDequeException e) { throw new EmptyStackException(); } }

87

slide-89
SLIDE 89

Definition of stacks from deques

public T top() throws EmptyStackException { try { return deque.last(); } catch (EmptyDequeException e) { throw new EmptyStackException(); } }

88

slide-90
SLIDE 90

Implementation of deques based

  • n lists
  • Singly-linked lists are not appropriate

because removeLast requires the whole list to be traversed, in order to get the reference of the last-but-one node

  • Solution: doubly-linked lists

89

slide-91
SLIDE 91

Doubly Linked Lists

  • Linked lists in which each node has an

additional reference pointing to the previous node in the list

– Can be traversed both from the beginning to the end and vice-versa – removeLast does not need the whole list to be traversed

top

info next prev info next prev info next prev

null null tail

90

slide-92
SLIDE 92

The DLNode class

Public class DLNode<T> { private T info; private DLNode<T> next; private DLNode<T> prev; public DLNode(T info) {…} public DLNode(T info, DLNode prev, DLNode next) {…} public DLNode<T> getNext() {…} public void setNext(DLNode<T> next) {…} public DLNode<T> getPrev() {…} public void setPrev(DLNode<T> prev) {…} public T getInfo() {…} public void setInfo(T info) {…} }

91

slide-93
SLIDE 93

Inserting a node

top node

DLNode<T> node = new DLNode<T>(data);

prev null null null null tail

92

slide-94
SLIDE 94

Inserting a node

top node

node.setPrev(prev); if (prev != null) { node.setNext(prev.getNext()); prev.setNext(node); }

prev null null tail

93

slide-95
SLIDE 95

Inserting a node

top node

if (prev == null) { node.setNext(top); top = node; } if (node.getNext() != null) { node.getNext().setPrev(node); } else { tail = node; }

prev null null tail

94

slide-96
SLIDE 96

Inserting a node

/** * Inserts ‘data’ after the ‘prev’ node. If ‘prev’ * is null, ‘data’ is inserted at the first position */ public void insert(DLNode prev, T data) { DLNode<T> node = new DLNode<T>(data); node.setPrev(prev); if (prev != null) { node.setNext(prev.getNext()); prev.setNext(node); } else { node.setNext(top); top = node; } if (node.getNext() != null) { node.getNext().setPrev(node); } else { tail = node; } }

95

slide-97
SLIDE 97

Removing a node

top

T data = removed.getInfo();

removed null null tail data

96

slide-98
SLIDE 98

Removing a node

top

if (removed.getPrev() != null) { removed.getPrev().setNext(removed.getNext()); } else { top = removed.getNext(); }

removed null null tail data

97

slide-99
SLIDE 99

Removing a node

top

if (removed.getNext() != null) { removed.getNext().setPrev(removed.getPrev()); } else { tail = removed.getPrev(); }

removed null null tail data

98

slide-100
SLIDE 100

Removing a node

top null null tail data

99

slide-101
SLIDE 101

Removing a node

/** * Removes a node from the list and returns * the information it holds. */ public T remove(DLNode<T> removed) { T data = removed.getInfo(); if (removed.getPrev() != null) { removed.getPrev().setNext(removed.getNext()); } else { top = removed.getNext(); } if (removed.getNext() != null) { removed.getNext().setPrev(removed.getPrev()); } else { tail = removed.getPrev(); } return data; }

100

slide-102
SLIDE 102

Alternate implementation

  • Checking that the previous and next

nodes are not null makes the previous implementation complex and error-prone

  • Possible simplification:

– Create two special (dummy) nodes, without associated info, so that one is always at the beginning of the list and the other one is always at the end:

  • An empty list contains only those two empty nodes
  • For insertions and removals, it is guaranteed that

the previous and next nodes exists, so there is no need to check them

  • References top and tail do not need to be

updated

101

slide-103
SLIDE 103

Alternate implementation

top null null tail null null null

102

slide-104
SLIDE 104

Implementation based on lists

public class DLDeque<T> implements Deque<T> { private DLNode<T>top, tail; private int size; public DLDeque() { top = new DLNode<T>(); tail = new DLNode<T>(); tail.setPrev(top); top.setNext(tail); size = 0; } …

103

slide-105
SLIDE 105

Insertion

Madrid Miami Munich Moscow

first second top tail

104

slide-106
SLIDE 106

Implementation based on lists

… public void insertFirst(T info) { DLNode<T> second = top.getNext(); DLNode<T> first = new DLNode<T>(info, top, second); second.setPrev(first); top.setNext(first); size++; } …

105

slide-107
SLIDE 107

Extraction

Madrid Miami Munich Moscow

first top second tail

106

slide-108
SLIDE 108

Implementation based on lists

public T removeFirst() throws EmptyDequeException { if (top.getNext() == tail) throw new EmptyDequeException(); DLNode<T> first = top.getNext(); T info = first.getInfo(); DLNode<T> second = first.getNext(); top.setNext(second); second.setPrev(top); size--; return info; }

107

slide-109
SLIDE 109

Activity

  • Review how “queues” are implemented in

– http://docs.oracle.com/javase/tutorial/collections/in terfaces/queue.html – http://docs.oracle.com/javase/6/docs/api/java/util/Qu eue.html

108

slide-110
SLIDE 110

Priority queue

  • A priority queue is a linear data

structure where elements are retuned according to a value associated to them (priority) (and not necessarily to the

  • rder of insertion)
  • The priority might be the value of the

element itself, but it might also differ from it

109

slide-111
SLIDE 111

Interface for priority queues

public interface PriorityQueue<T> { public int size(); public boolean isEmpty(); public void insertItem(Comparable priority, T info); public T minElem() throws EmptyPriorityQueueException; public T removeMinElem() throws EmptyPriorityQueueException; public T minKey() throws EmptyPriorityQueueException; }

110

slide-112
SLIDE 112

Example

2 1 3 2 4 1 5 2 1 3 2 1 + + + – + – + – + + + – + – + – 4 5 3 3

111

slide-113
SLIDE 113

Example

2 1 3 2 4 1 5 2 1 3 2 1 + + + – + – + – + + + – + – + – 4 5 3 3 min min min

112

slide-114
SLIDE 114

Example

2 5 3 2 4 1 5 2 1 3 2 + + + – + – + – + + + – + – + – 1 1 3 3 4 insert in order insert in order insert in order insert in order insert in order

113

slide-115
SLIDE 115

Implementations

  • With an unsorted sequence

– Easy insertion – Comparison needed for extraction

  • With a sorted sequence

– Comparison needed for insertion – Easy extraction

114

slide-116
SLIDE 116

Activity

  • Try

http://www.akira.ruc.dk/~keld/algoritmik_e99/Applets/ Chap11/PriorityQ/PriorityQ.html

115