Linear Data StructuresLinear Data Structures
Lists, Stacks, QueuesLists, Stacks, Queues
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
Table of ContentsTable of Contents
1.1. Abstract Data Types (ADT)Abstract Data Types (ADT)
2.2. Lists – TheLists – The ListList<T><T> ClassClass
 Static and LinkedStatic and Linked
1.1. Stacks – TheStacks – The Stack<T>Stack<T> ClassClass
 Static and LinkedStatic and Linked
1.1. Queues – TheQueues – The Queue<T>Queue<T> ClassClass
 Circular and LinkedCircular and Linked
 Priority QueuePriority Queue
 C# ImplementationC# Implementation
Abstract DataTypesAbstract DataTypes
Basic Data StructuresBasic Data Structures
Abstract Data TypesAbstract Data Types
 An Abstract Data Type (ADT) is a data typeAn Abstract Data Type (ADT) is a data type
together with the operations, whosetogether with the operations, whose
properties are specified independently of anyproperties are specified independently of any
particular implementationparticular implementation
ADT are set of definitions of operations (like theADT are set of definitions of operations (like the
interfaces in C#)interfaces in C#)
Can have several different implementationsCan have several different implementations
Different implementations can have differentDifferent implementations can have different
efficiencyefficiency
Basic Data StructuresBasic Data Structures
 Linear structuresLinear structures
Lists: fixed size and variable sizeLists: fixed size and variable size
Stacks: LIFO (Last In First Out) structureStacks: LIFO (Last In First Out) structure
Queues: FIFO (First In First Out) structureQueues: FIFO (First In First Out) structure
 TreesTrees
Binary, ordered, balanced, etc.Binary, ordered, balanced, etc.
 Dictionaries (maps)Dictionaries (maps)
Contain pairs (key, value)Contain pairs (key, value)
Hash tables: use hash functions to search/insertHash tables: use hash functions to search/insert
ListsLists
Static and DynamicStatic and Dynamic
ImplementationsImplementations
The List ADTThe List ADT
 Data structure (container) that containsData structure (container) that contains
a sequence of elementsa sequence of elements
Can have variable sizeCan have variable size
Elements are arranged linearly, in sequenceElements are arranged linearly, in sequence
 Can be implemented in several waysCan be implemented in several ways
Statically (using arrayStatically (using array  fixed size)fixed size)
Dynamically (linked implementation)Dynamically (linked implementation)
Using resizable array (theUsing resizable array (the List<T>List<T> class)class)
Static ListStatic List
 Implemented by an arrayImplemented by an array
Provides direct access by indexProvides direct access by index
Has fixed capacityHas fixed capacity
Insertion, deletion and resizing are slowInsertion, deletion and resizing are slow
operationsoperations
LL 22 1818 77 1212 33 66 1111 99
0 1 2 3 4 5 6 7
Linked ListLinked List
 Dynamic (pointer-based) implementationDynamic (pointer-based) implementation
 Different formsDifferent forms
Singly-linked and doubly-linkedSingly-linked and doubly-linked
Sorted and unsortedSorted and unsorted
 Singly-linked listSingly-linked list
EachEach itemitem has 2 fields:has 2 fields: valuevalue andand nextnext
22
nextnext
77
nextnextheadhead
44
nextnext
55
nextnext
nullnull
Linked List (2)Linked List (2)
 Doubly-linked ListDoubly-linked List
Each item has 3 fields:Each item has 3 fields: valuevalue,, nextnext andand prevprev
22
nextnext
prevprev
headhead
nullnull
77
nextnext
prevprev
nullnull
44
nextnext
prevprev
55
nextnext
prevprev
tailtail
TheThe ListList<T><T> ClassClass
Auto-Resizable Indexed ListsAuto-Resizable Indexed Lists
TheThe List<T>List<T> ClassClass
 Implements the abstract data structureImplements the abstract data structure listlist
using an arrayusing an array
All elements are of the same typeAll elements are of the same type TT
TT can be any type, e.g.can be any type, e.g. List<int>List<int>,,
List<string>List<string>,, List<DateTime>List<DateTime>
Size is dynamically increased as neededSize is dynamically increased as needed
 Basic functionality:Basic functionality:
CountCount – returns the number of elements– returns the number of elements
Add(T)Add(T) – appends given element at the end– appends given element at the end
List<T>List<T> – Simple Example– Simple Example
static void Main()static void Main()
{{
List<string> list = new List<string>() { "C#",List<string> list = new List<string>() { "C#",
"Java" };"Java" };
list.Add("SQL");list.Add("SQL");
list.Add("Python");list.Add("Python");
foreach (string item in list)foreach (string item in list)
{{
Console.WriteLine(item);Console.WriteLine(item);
}}
// Result:// Result:
// C#// C#
// Java// Java
// SQL// SQL
// Python// Python
}}
Inline initialization:Inline initialization:
the compiler addsthe compiler adds
specified elementsspecified elements
to the list.to the list.
List<T>List<T> – Simple Example– Simple Example
Live DemoLive Demo
List<T>List<T> – Functionality– Functionality
 list[index]list[index] – access element by index– access element by index
 Insert(indexInsert(index,, T)T) – inserts given element to the– inserts given element to the
list at a specified positionlist at a specified position
 Remove(T)Remove(T) – removes the first occurrence of– removes the first occurrence of
given elementgiven element
 RemoveAt(index)RemoveAt(index) – removes the element at the– removes the element at the
specified positionspecified position
 Clear()Clear() – removes all elements– removes all elements
 Contains(TContains(T)) – determines whether an element– determines whether an element
is part of the listis part of the list
List<T>List<T> – Functionality (2)– Functionality (2)
 IndexOf()IndexOf() – returns the index of the first– returns the index of the first
occurrence of a valueoccurrence of a value in the listin the list ((zero-basedzero-based))
 Reverse()Reverse() – reverses the order of the elements in– reverses the order of the elements in
the list or a portion of itthe list or a portion of it
 Sort()Sort() – sorts the elements in the list or a– sorts the elements in the list or a
portion of itportion of it
 ToArray()ToArray() – converts the elements of the list to– converts the elements of the list to
an arrayan array
 TrimExcess()TrimExcess() – sets the capacity to the actual– sets the capacity to the actual
number of elementsnumber of elements
Primes in an Interval – ExamplePrimes in an Interval – Example
static List<int> FindPrimes(int start, int end)static List<int> FindPrimes(int start, int end)
{{
List<int> primesList = new List<int>();List<int> primesList = new List<int>();
for (int num = start; num <= end; num++)for (int num = start; num <= end; num++)
{{
bool prime = true;bool prime = true;
for (int div = 2; div <= Math.Sqrt(num); div++)for (int div = 2; div <= Math.Sqrt(num); div++)
{{
if (num % div == 0)if (num % div == 0)
{{
prime = false;prime = false;
break;break;
}}
}}
if (prime)if (prime)
{{
primesList.Add(num);primesList.Add(num);
}}
}}
return primesList;return primesList;
}}
PrimesPrimes in anin an
IntervalInterval
Live DemoLive Demo
Union and Intersection – ExampleUnion and Intersection – Example
int[] Union(int[] firstArr, int[] secondArr)int[] Union(int[] firstArr, int[] secondArr)
{{
List<int> union = new List<int>();List<int> union = new List<int>();
union.AddRange(firstArray);union.AddRange(firstArray);
foreach (int item in secondArray)foreach (int item in secondArray)
if (! union.Contains(item))if (! union.Contains(item))
union.Add(item);union.Add(item);
return union.ToArray();return union.ToArray();
}}
int[] Intersection(int[] firstArr, int[] secondArr)int[] Intersection(int[] firstArr, int[] secondArr)
{{
List<int> intersect = new List<int>();List<int> intersect = new List<int>();
foreach (int item in firstArray)foreach (int item in firstArray)
if (Array.IndexOf(secondArray, item) != -1)if (Array.IndexOf(secondArray, item) != -1)
intersect.Add(item);intersect.Add(item);
return intersect.ToArray();return intersect.ToArray();
}}
Union and IntersectionUnion and Intersection
Live DemoLive Demo
StacksStacks
Static and Dynamic ImplementationStatic and Dynamic Implementation
The Stack ADTThe Stack ADT
 LIFO (Last In First Out) structureLIFO (Last In First Out) structure
 Elements inserted (push) at “top”Elements inserted (push) at “top”
 Elements removed (pop) from “top”Elements removed (pop) from “top”
 Useful in many situationsUseful in many situations
E.g. the execution stack of the programE.g. the execution stack of the program
 Can be implemented in several waysCan be implemented in several ways
Statically (using array)Statically (using array)
Dynamically (linked implementation)Dynamically (linked implementation)
Using theUsing the Stack<T>Stack<T> classclass
Static StackStatic Stack
 Static (array-based) implementationStatic (array-based) implementation
Has limited (fixed) capacityHas limited (fixed) capacity
The current index (The current index (toptop) moves left / right with) moves left / right with
each pop / pusheach pop / push
SS 22 1818 77 1212
0 1 2 3 4 5 6 7
toptop
Linked StackLinked Stack
 Dynamic (pointer-based) implementationDynamic (pointer-based) implementation
EachEach itemitem has 2 fields:has 2 fields: valuevalue andand nextnext
Special pointer keeps the top elementSpecial pointer keeps the top element
22
nextnext
77
nextnext
toptop
44
nextnext
55
nextnext
nullnull
TheThe Stack<T>Stack<T> ClassClass
The Standard Stack Implementation in .NETThe Standard Stack Implementation in .NET
TheThe Stack<T>Stack<T> ClassClass
 Implements theImplements the stackstack data structure using andata structure using an
arrayarray
 Elements are from the same typeElements are from the same type TT
 TT can be any type, e.g.can be any type, e.g. Stack<int>Stack<int>
 Size is dynamically increased as neededSize is dynamically increased as needed
 Basic functionality:Basic functionality:
 Push(T)Push(T) – inserts elements to the stack– inserts elements to the stack
 Pop()Pop() – removes and returns the top element– removes and returns the top element
from the stackfrom the stack
TheThe Stack<T>Stack<T> Class (2)Class (2)
 Basic functionality:Basic functionality:
 Peek()Peek() – returns the top element of the stack– returns the top element of the stack
without removing itwithout removing it
 CountCount – returns the number of elements– returns the number of elements
 Clear()Clear() – removes all elements– removes all elements
 Contains(T)Contains(T) – determines whether given– determines whether given
element is in the stackelement is in the stack
 ToArray()ToArray() – converts the stack to an array– converts the stack to an array
 TrimExcess()TrimExcess() – sets the capacity to– sets the capacity to
the actual number of elementsthe actual number of elements
Stack<T>Stack<T> – Example– Example
 UsingUsing Push()Push(),, Pop()Pop() andand Peek()Peek() methodsmethods
static void Main()static void Main()
{{
Stack<string> stack = new Stack<string>();Stack<string> stack = new Stack<string>();
stack.Push("1. Ivan");stack.Push("1. Ivan");
stack.Push("2. Nikolay");stack.Push("2. Nikolay");
stack.Push("3. Maria");stack.Push("3. Maria");
stack.Push("4. George");stack.Push("4. George");
Console.WriteLine("Top = {0}", stack.Peek());Console.WriteLine("Top = {0}", stack.Peek());
while (stack.Count > 0)while (stack.Count > 0)
{{
string personName = stack.Pop();string personName = stack.Pop();
Console.WriteLine(personName);Console.WriteLine(personName);
}}
}}
Stack<T>Stack<T>
Live DemoLive Demo
Matching Brackets – ExampleMatching Brackets – Example
 We are given an arithmetical expression withWe are given an arithmetical expression with
brackets that can be nestedbrackets that can be nested
 Goal: extract all sub-expressions in bracketsGoal: extract all sub-expressions in brackets
 Example:Example:
 1 + (2 - (2+3) * 4 / (3+1)) * 51 + (2 - (2+3) * 4 / (3+1)) * 5
 Result:Result:
 (2+3)(2+3) || (3+1)(3+1) || (2 - (2+3) * 4 / (3+1))(2 - (2+3) * 4 / (3+1))
 Algorithm:Algorithm:
 For each 'For each '((' push its index in a stack' push its index in a stack
 For each 'For each '))' pop the corresponding start index' pop the corresponding start index
Matching Brackets – SolutionMatching Brackets – Solution
string expression = "1 + (2 - (2+3) * 4 / (3+1)) * 5";string expression = "1 + (2 - (2+3) * 4 / (3+1)) * 5";
Stack<int> stack = new Stack<int>();Stack<int> stack = new Stack<int>();
for (int index = 0; index < expression.Length; index++)for (int index = 0; index < expression.Length; index++)
{{
char ch = expression[index];char ch = expression[index];
if (ch == '(')if (ch == '(')
{{
stack.Push(index);stack.Push(index);
}}
else if (ch == ')')else if (ch == ')')
{{
int startIndex = stack.Pop();int startIndex = stack.Pop();
int length = index - startIndex + 1;int length = index - startIndex + 1;
string contents =string contents =
expression.Substring(startIndex, length);expression.Substring(startIndex, length);
Console.WriteLine(contents);Console.WriteLine(contents);
}}
}}
Matching BracketsMatching Brackets
Live DemoLive Demo
QueuesQueues
Static and Dynamic ImplementationStatic and Dynamic Implementation
The Queue ADTThe Queue ADT
 FIFO (First In First Out) structureFIFO (First In First Out) structure
 Elements inserted at the tail (Enqueue)Elements inserted at the tail (Enqueue)
 Elements removed from the head (Elements removed from the head (DequeueDequeue))
 Useful in many situationsUseful in many situations
Print queues, message queues, etc.Print queues, message queues, etc.
 Can be implemented in several waysCan be implemented in several ways
Statically (using array)Statically (using array)
Dynamically (using pointers)Dynamically (using pointers)
Using theUsing the Queue<T>Queue<T> classclass
Static QueueStatic Queue
 Static (array-based) implementationStatic (array-based) implementation
Has limited (fixed) capacityHas limited (fixed) capacity
Implement as a “circular array”Implement as a “circular array”
HasHas headhead andand tailtail indices, pointing to theindices, pointing to the
head and the tail of the cyclic queuehead and the tail of the cyclic queue
SS 77 1212 22 55
0 1 2 3 4 5 6 7
headhead tailtail
Linked QueueLinked Queue
 Dynamic (pointer-based) implementationDynamic (pointer-based) implementation
Each item has 2 fields:Each item has 2 fields: valuevalue andand nextnext
Dynamically create and delete objectsDynamically create and delete objects
22
nextnext
77
nextnext
headhead
44
nextnext
55
nextnext
nullnull
tailtail
TheThe Queue<T>Queue<T> ClassClass
Standard Queue Implementation in .NETStandard Queue Implementation in .NET
TheThe Queue<T>Queue<T> ClassClass
 Implements the queue data structure using aImplements the queue data structure using a
circular resizable arraycircular resizable array
 Elements are from the same typeElements are from the same type TT
 TT can be any type, e.g.can be any type, e.g. Stack<int>Stack<int>
 Size is dynamically increased as neededSize is dynamically increased as needed
 Basic functionality:Basic functionality:
 Enqueue(T)Enqueue(T) – adds an element to the– adds an element to the
end of the queueend of the queue
 Dequeue()Dequeue() – removes and returns the– removes and returns the
element at the beginning of the queueelement at the beginning of the queue
TheThe Queue<T>Queue<T> Class (2)Class (2)
 Basic functionality:Basic functionality:
 Peek()Peek() – returns the element at the beginning– returns the element at the beginning
of the queue without removing itof the queue without removing it
 CountCount – returns the number of elements– returns the number of elements
 Clear()Clear() – removes all elements– removes all elements
 Contains(T)Contains(T) – determines whether given– determines whether given
element is in the queueelement is in the queue
 ToArray()ToArray() – converts the queue to an array– converts the queue to an array
 TrimExcess()TrimExcess() – sets the capacity to the– sets the capacity to the
actual number of elements in the queueactual number of elements in the queue
Queue<T>Queue<T> –– ExampleExample
 UsingUsing Enqueue()Enqueue() andand Dequeue()Dequeue() methodsmethods
static void Main()static void Main()
{{
Queue<string> queue = new Queue<string>();Queue<string> queue = new Queue<string>();
queue.Enqueue("Message One");queue.Enqueue("Message One");
queue.Enqueue("Message Two");queue.Enqueue("Message Two");
queue.Enqueue("Message Three");queue.Enqueue("Message Three");
queue.Enqueue("Message Four");queue.Enqueue("Message Four");
while (queue.Count > 0)while (queue.Count > 0)
{{
string message = queue.Dequeue();string message = queue.Dequeue();
Console.WriteLine(message);Console.WriteLine(message);
}}
}}
TheThe Queue<T>Queue<T> ClassClass
Live DemoLive Demo
 We are given the sequence:We are given the sequence:
S =S = NN,, N+1N+1,, 2*N2*N,, N+2N+2,, 2*(N+1)2*(N+1),, 2*N+12*N+1,, 4*N4*N,, ……
 Find the first index of given number PFind the first index of given number P
 Example: N =Example: N = 33, P =, P = 1616
S =S = 33,, 44,, 66,, 55,, 88,, 77,, 1212,, 66,, 1010,, 99,, 1616,, 88,, 1414,, ……
Index of P =Index of P = 1111
Sequence N, N+1, 2*NSequence N, N+1, 2*N
+1+1
*2*2
+1+1
*2*2
+1+1
*2*2
Sequence – Solution with a QueueSequence – Solution with a Queue
int n = 3, p = 16;int n = 3, p = 16;
Queue<int> queue = new Queue<int>();Queue<int> queue = new Queue<int>();
queue.Enqueue(n);queue.Enqueue(n);
int index = 0;int index = 0;
while (queue.Count > 0)while (queue.Count > 0)
{{
int current = queue.Dequeue();int current = queue.Dequeue();
index++;index++;
if (current == p)if (current == p)
{{
Console.WriteLine("Index = {0}", index);Console.WriteLine("Index = {0}", index);
return;return;
}}
queue.Enqueue(current+1);queue.Enqueue(current+1);
queue.Enqueue(2*current);queue.Enqueue(2*current);
}}
Sequence N, N+1, 2*NSequence N, N+1, 2*N
Live DemoLive Demo
Priority QueuePriority Queue
Priority QueuePriority Queue
 What is aWhat is a PriorityPriority QueueQueue
Data type to efficiently support finding the itemData type to efficiently support finding the item
with the highest prioritywith the highest priority
Basic operationsBasic operations
 Enqueue(T element)Enqueue(T element)
 DequeueDequeue
 There is no build-inThere is no build-in PriorityPriority QueueQueue in .NETin .NET
Can be easily implemented usingCan be easily implemented using
PowerCollectionsPowerCollections
Priority Queue ImplementationPriority Queue Implementation
class PriorityQueue<T> where T:IComparable<T>class PriorityQueue<T> where T:IComparable<T>
{{
private OrderedBag<T> bag;private OrderedBag<T> bag;
publicpublic intint CountCount
{{
get { returnget { return bag.Countbag.Count; }; }
private set{ }private set{ }
}}
public PriorityQueue()public PriorityQueue()
{{
bag = newbag = new OrderedBag<TOrderedBag<T>();>();
}}
public void Enqueue(T element)public void Enqueue(T element)
{{
bag.Add(elementbag.Add(element););
}}
public T Dequeue()public T Dequeue()
{{
var element = bag.GetFirst();var element = bag.GetFirst();
bag.RemoveFirstbag.RemoveFirst();();
return element;return element;
}}
}}
47
Necessary to provideNecessary to provide
comparable elementscomparable elements
Priority Queue AdditionalPriority Queue Additional
NotesNotes
 The generic type is needed to implementThe generic type is needed to implement
IComparable<T>IComparable<T>
 It is not necessary to useIt is not necessary to use OrderedBagOrderedBag
Other Data Structures also can be usedOther Data Structures also can be used
 Adding and Removing Element in theAdding and Removing Element in the PriorityPriority
QueueQueue is with complexity logNis with complexity logN
 Keeps the elements SortedKeeps the elements Sorted
Always returns the best element that fulfillsAlways returns the best element that fulfills
some conditionsome condition
 E.g. the smallest or the biggest elementE.g. the smallest or the biggest element
48
Priority QueuePriority Queue
Live DemoLive Demo
49
SummarySummary
 ADT are defined by list of operations independentADT are defined by list of operations independent
of their implementationof their implementation
 The basic linear data structures in the computerThe basic linear data structures in the computer
programming are:programming are:
 List (static, linked)List (static, linked)
 Implemented by theImplemented by the ListList<T><T> class in .NETclass in .NET
 Stack (static, linked)Stack (static, linked)
 Implemented by theImplemented by the StackStack<T><T> class in .NETclass in .NET
 Queue (static, linked)Queue (static, linked)
 Implemented by theImplemented by the QueueQueue<T><T> class in .NETclass in .NET
 Priority QueuePriority Queue
 Implemented by theImplemented by the OrderedBag<T>OrderedBag<T> classclass
Linear Data StructuresLinear Data Structures
Questions?Questions?
http://academy.telerik.com
ExercisesExercises
1.1. Write a program that reads from the console aWrite a program that reads from the console a
sequence of positive integer numbers. The sequencesequence of positive integer numbers. The sequence
ends when empty line is entered. Calculate and printends when empty line is entered. Calculate and print
the sum and average of the elements of thethe sum and average of the elements of the
sequence. Keep the sequence insequence. Keep the sequence in List<int>List<int>..
2.2. Write a program that reads N integers from theWrite a program that reads N integers from the
console and reverses them using a stack. Use theconsole and reverses them using a stack. Use the
Stack<int>Stack<int> class.class.
3.3. Write a program that reads a sequence of integersWrite a program that reads a sequence of integers
((List<int>List<int>) ending with an empty line and sorts) ending with an empty line and sorts
them in an increasing order.them in an increasing order.
Exercises (2)Exercises (2)
4.4. Write a method that finds the longest subsequenceWrite a method that finds the longest subsequence
of equal numbers in givenof equal numbers in given List<int>List<int> and returnsand returns
the result as newthe result as new List<int>List<int>. Write a program to. Write a program to
test whether the method works correctly.test whether the method works correctly.
5.5. Write a program that removes from given sequenceWrite a program that removes from given sequence
all negative numbers.all negative numbers.
6.6. Write a program that removes from given sequenceWrite a program that removes from given sequence
all numbers that occur odd number of times.all numbers that occur odd number of times.
Example:Example:
{4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2}{4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2}  {5, 3, 3, 5}{5, 3, 3, 5}
Exercises (3)Exercises (3)
7.7. Write a program that finds in given array of integersWrite a program that finds in given array of integers
(all belonging to the range [0..1000]) how many(all belonging to the range [0..1000]) how many
times each of them occurs.times each of them occurs.
Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2}Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2}
22  2 times2 times
33  4 times4 times
44  3 times3 times
8.8. * The majorant of an array of size N is a value that* The majorant of an array of size N is a value that
occurs in it at least N/2 + 1 times. Write a program tooccurs in it at least N/2 + 1 times. Write a program to
find the majorant of given array (if exists). Example:find the majorant of given array (if exists). Example:
{2, 2, 3, 3, 2, 3, 4, 3, 3}{2, 2, 3, 3, 2, 3, 4, 3, 3}  33
Exercises (4)Exercises (4)
9.9. We are given the following sequence:We are given the following sequence:
SS11 = N;= N;
SS22 = S= S11 + 1;+ 1;
SS33 = 2*S= 2*S11 + 1;+ 1;
SS44 = S= S11 + 2;+ 2;
SS55 = S= S22 + 1;+ 1;
SS66 = 2*S= 2*S22 + 1;+ 1;
SS77 = S= S22 + 2;+ 2;
......
Using theUsing the Queue<T>Queue<T> class write a program to printclass write a program to print
its first 50 members for given N.its first 50 members for given N.
Example: N=2Example: N=2  2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...
Exercises (5)Exercises (5)
10.10. We are given numbers N and M and the followingWe are given numbers N and M and the following
operations:operations:
a)a) N = N+1N = N+1
b)b) N = N+2N = N+2
c)c) N = N*2N = N*2
Write a program that finds the shortest sequence ofWrite a program that finds the shortest sequence of
operations from the list above that starts from N andoperations from the list above that starts from N and
finishes in M. Hint: use a queue.finishes in M. Hint: use a queue.
 Example: N = 5, M = 16Example: N = 5, M = 16
 Sequence: 5Sequence: 5  77  88  1616
Exercises (6)Exercises (6)
11.11. Write a classWrite a class StudentStudent, that has three fields:, that has three fields: namename
(String),(String), ageage(Integer) and(Integer) and
paidSemesterOnlinepaidSemesterOnline(Boolean). When in a queue(Boolean). When in a queue
the students who paid online are with higherthe students who paid online are with higher
priority than those who are about to pay thepriority than those who are about to pay the
semester. Write a program which with a givensemester. Write a program which with a given
queue of student determine whose turn it is. Hint:queue of student determine whose turn it is. Hint:
use priority queueuse priority queue
57
Exercises (6)Exercises (6)
12.12. Implement the data structureImplement the data structure linked listlinked list. Define a. Define a
classclass ListItem<T>ListItem<T> that has two fields:that has two fields: valuevalue (of(of
typetype TT) and) and nextItemnextItem (of type(of type ListItem<T>ListItem<T>).).
Define additionally a classDefine additionally a class LinkedList<T>LinkedList<T> with awith a
single fieldsingle field firstElementfirstElement (of type(of type ListItem<T>ListItem<T>).).
13.13. Implement the ADTImplement the ADT stackstack as auto-resizable array.as auto-resizable array.
Resize the capacity on demand (when no space isResize the capacity on demand (when no space is
available to add / insert a new element).available to add / insert a new element).
14.14. Implement the ADTImplement the ADT queuequeue as dynamic linked list.as dynamic linked list.
Use generics (Use generics (LinkedQueue<T>LinkedQueue<T>) to allow storing) to allow storing
different data types in the queue.different data types in the queue.
Exercises (7)Exercises (7)
15.15. * We are given a labyrinth of size N x N. Some of its* We are given a labyrinth of size N x N. Some of its
cells are empty (cells are empty (00) and some are full () and some are full (xx). We can). We can
move from an empty cell to another empty cell ifmove from an empty cell to another empty cell if
they share common wall. Given a starting positionthey share common wall. Given a starting position
((**) calculate and fill in the array the minimal) calculate and fill in the array the minimal
distance from this position to any other cell in thedistance from this position to any other cell in the
array. Use "array. Use "uu" for all unreachable cells. Example:" for all unreachable cells. Example:
00 00 00 xx 00 xx
00 xx 00 xx 00 xx
00 ** xx 00 xx 00
00 xx 00 00 00 00
00 00 00 xx xx 00
00 00 00 xx 00 xx
33 44 55 xx uu xx
22 xx 66 xx uu xx
11 ** xx 88 xx 1010
22 xx 66 77 88 99
33 44 55 xx xx 1010
44 55 66 xx uu xx

16 Linear data structures

  • 1.
    Linear Data StructuresLinearData Structures Lists, Stacks, QueuesLists, Stacks, Queues Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2.
    Table of ContentsTableof Contents 1.1. Abstract Data Types (ADT)Abstract Data Types (ADT) 2.2. Lists – TheLists – The ListList<T><T> ClassClass  Static and LinkedStatic and Linked 1.1. Stacks – TheStacks – The Stack<T>Stack<T> ClassClass  Static and LinkedStatic and Linked 1.1. Queues – TheQueues – The Queue<T>Queue<T> ClassClass  Circular and LinkedCircular and Linked  Priority QueuePriority Queue  C# ImplementationC# Implementation
  • 3.
    Abstract DataTypesAbstract DataTypes BasicData StructuresBasic Data Structures
  • 4.
    Abstract Data TypesAbstractData Types  An Abstract Data Type (ADT) is a data typeAn Abstract Data Type (ADT) is a data type together with the operations, whosetogether with the operations, whose properties are specified independently of anyproperties are specified independently of any particular implementationparticular implementation ADT are set of definitions of operations (like theADT are set of definitions of operations (like the interfaces in C#)interfaces in C#) Can have several different implementationsCan have several different implementations Different implementations can have differentDifferent implementations can have different efficiencyefficiency
  • 5.
    Basic Data StructuresBasicData Structures  Linear structuresLinear structures Lists: fixed size and variable sizeLists: fixed size and variable size Stacks: LIFO (Last In First Out) structureStacks: LIFO (Last In First Out) structure Queues: FIFO (First In First Out) structureQueues: FIFO (First In First Out) structure  TreesTrees Binary, ordered, balanced, etc.Binary, ordered, balanced, etc.  Dictionaries (maps)Dictionaries (maps) Contain pairs (key, value)Contain pairs (key, value) Hash tables: use hash functions to search/insertHash tables: use hash functions to search/insert
  • 6.
    ListsLists Static and DynamicStaticand Dynamic ImplementationsImplementations
  • 7.
    The List ADTTheList ADT  Data structure (container) that containsData structure (container) that contains a sequence of elementsa sequence of elements Can have variable sizeCan have variable size Elements are arranged linearly, in sequenceElements are arranged linearly, in sequence  Can be implemented in several waysCan be implemented in several ways Statically (using arrayStatically (using array  fixed size)fixed size) Dynamically (linked implementation)Dynamically (linked implementation) Using resizable array (theUsing resizable array (the List<T>List<T> class)class)
  • 8.
    Static ListStatic List Implemented by an arrayImplemented by an array Provides direct access by indexProvides direct access by index Has fixed capacityHas fixed capacity Insertion, deletion and resizing are slowInsertion, deletion and resizing are slow operationsoperations LL 22 1818 77 1212 33 66 1111 99 0 1 2 3 4 5 6 7
  • 9.
    Linked ListLinked List Dynamic (pointer-based) implementationDynamic (pointer-based) implementation  Different formsDifferent forms Singly-linked and doubly-linkedSingly-linked and doubly-linked Sorted and unsortedSorted and unsorted  Singly-linked listSingly-linked list EachEach itemitem has 2 fields:has 2 fields: valuevalue andand nextnext 22 nextnext 77 nextnextheadhead 44 nextnext 55 nextnext nullnull
  • 10.
    Linked List (2)LinkedList (2)  Doubly-linked ListDoubly-linked List Each item has 3 fields:Each item has 3 fields: valuevalue,, nextnext andand prevprev 22 nextnext prevprev headhead nullnull 77 nextnext prevprev nullnull 44 nextnext prevprev 55 nextnext prevprev tailtail
  • 11.
    TheThe ListList<T><T> ClassClass Auto-ResizableIndexed ListsAuto-Resizable Indexed Lists
  • 12.
    TheThe List<T>List<T> ClassClass Implements the abstract data structureImplements the abstract data structure listlist using an arrayusing an array All elements are of the same typeAll elements are of the same type TT TT can be any type, e.g.can be any type, e.g. List<int>List<int>,, List<string>List<string>,, List<DateTime>List<DateTime> Size is dynamically increased as neededSize is dynamically increased as needed  Basic functionality:Basic functionality: CountCount – returns the number of elements– returns the number of elements Add(T)Add(T) – appends given element at the end– appends given element at the end
  • 13.
    List<T>List<T> – SimpleExample– Simple Example static void Main()static void Main() {{ List<string> list = new List<string>() { "C#",List<string> list = new List<string>() { "C#", "Java" };"Java" }; list.Add("SQL");list.Add("SQL"); list.Add("Python");list.Add("Python"); foreach (string item in list)foreach (string item in list) {{ Console.WriteLine(item);Console.WriteLine(item); }} // Result:// Result: // C#// C# // Java// Java // SQL// SQL // Python// Python }} Inline initialization:Inline initialization: the compiler addsthe compiler adds specified elementsspecified elements to the list.to the list.
  • 14.
    List<T>List<T> – SimpleExample– Simple Example Live DemoLive Demo
  • 15.
    List<T>List<T> – Functionality–Functionality  list[index]list[index] – access element by index– access element by index  Insert(indexInsert(index,, T)T) – inserts given element to the– inserts given element to the list at a specified positionlist at a specified position  Remove(T)Remove(T) – removes the first occurrence of– removes the first occurrence of given elementgiven element  RemoveAt(index)RemoveAt(index) – removes the element at the– removes the element at the specified positionspecified position  Clear()Clear() – removes all elements– removes all elements  Contains(TContains(T)) – determines whether an element– determines whether an element is part of the listis part of the list
  • 16.
    List<T>List<T> – Functionality(2)– Functionality (2)  IndexOf()IndexOf() – returns the index of the first– returns the index of the first occurrence of a valueoccurrence of a value in the listin the list ((zero-basedzero-based))  Reverse()Reverse() – reverses the order of the elements in– reverses the order of the elements in the list or a portion of itthe list or a portion of it  Sort()Sort() – sorts the elements in the list or a– sorts the elements in the list or a portion of itportion of it  ToArray()ToArray() – converts the elements of the list to– converts the elements of the list to an arrayan array  TrimExcess()TrimExcess() – sets the capacity to the actual– sets the capacity to the actual number of elementsnumber of elements
  • 17.
    Primes in anInterval – ExamplePrimes in an Interval – Example static List<int> FindPrimes(int start, int end)static List<int> FindPrimes(int start, int end) {{ List<int> primesList = new List<int>();List<int> primesList = new List<int>(); for (int num = start; num <= end; num++)for (int num = start; num <= end; num++) {{ bool prime = true;bool prime = true; for (int div = 2; div <= Math.Sqrt(num); div++)for (int div = 2; div <= Math.Sqrt(num); div++) {{ if (num % div == 0)if (num % div == 0) {{ prime = false;prime = false; break;break; }} }} if (prime)if (prime) {{ primesList.Add(num);primesList.Add(num); }} }} return primesList;return primesList; }}
  • 18.
    PrimesPrimes in aninan IntervalInterval Live DemoLive Demo
  • 19.
    Union and Intersection– ExampleUnion and Intersection – Example int[] Union(int[] firstArr, int[] secondArr)int[] Union(int[] firstArr, int[] secondArr) {{ List<int> union = new List<int>();List<int> union = new List<int>(); union.AddRange(firstArray);union.AddRange(firstArray); foreach (int item in secondArray)foreach (int item in secondArray) if (! union.Contains(item))if (! union.Contains(item)) union.Add(item);union.Add(item); return union.ToArray();return union.ToArray(); }} int[] Intersection(int[] firstArr, int[] secondArr)int[] Intersection(int[] firstArr, int[] secondArr) {{ List<int> intersect = new List<int>();List<int> intersect = new List<int>(); foreach (int item in firstArray)foreach (int item in firstArray) if (Array.IndexOf(secondArray, item) != -1)if (Array.IndexOf(secondArray, item) != -1) intersect.Add(item);intersect.Add(item); return intersect.ToArray();return intersect.ToArray(); }}
  • 20.
    Union and IntersectionUnionand Intersection Live DemoLive Demo
  • 21.
    StacksStacks Static and DynamicImplementationStatic and Dynamic Implementation
  • 22.
    The Stack ADTTheStack ADT  LIFO (Last In First Out) structureLIFO (Last In First Out) structure  Elements inserted (push) at “top”Elements inserted (push) at “top”  Elements removed (pop) from “top”Elements removed (pop) from “top”  Useful in many situationsUseful in many situations E.g. the execution stack of the programE.g. the execution stack of the program  Can be implemented in several waysCan be implemented in several ways Statically (using array)Statically (using array) Dynamically (linked implementation)Dynamically (linked implementation) Using theUsing the Stack<T>Stack<T> classclass
  • 23.
    Static StackStatic Stack Static (array-based) implementationStatic (array-based) implementation Has limited (fixed) capacityHas limited (fixed) capacity The current index (The current index (toptop) moves left / right with) moves left / right with each pop / pusheach pop / push SS 22 1818 77 1212 0 1 2 3 4 5 6 7 toptop
  • 24.
    Linked StackLinked Stack Dynamic (pointer-based) implementationDynamic (pointer-based) implementation EachEach itemitem has 2 fields:has 2 fields: valuevalue andand nextnext Special pointer keeps the top elementSpecial pointer keeps the top element 22 nextnext 77 nextnext toptop 44 nextnext 55 nextnext nullnull
  • 25.
    TheThe Stack<T>Stack<T> ClassClass TheStandard Stack Implementation in .NETThe Standard Stack Implementation in .NET
  • 26.
    TheThe Stack<T>Stack<T> ClassClass Implements theImplements the stackstack data structure using andata structure using an arrayarray  Elements are from the same typeElements are from the same type TT  TT can be any type, e.g.can be any type, e.g. Stack<int>Stack<int>  Size is dynamically increased as neededSize is dynamically increased as needed  Basic functionality:Basic functionality:  Push(T)Push(T) – inserts elements to the stack– inserts elements to the stack  Pop()Pop() – removes and returns the top element– removes and returns the top element from the stackfrom the stack
  • 27.
    TheThe Stack<T>Stack<T> Class(2)Class (2)  Basic functionality:Basic functionality:  Peek()Peek() – returns the top element of the stack– returns the top element of the stack without removing itwithout removing it  CountCount – returns the number of elements– returns the number of elements  Clear()Clear() – removes all elements– removes all elements  Contains(T)Contains(T) – determines whether given– determines whether given element is in the stackelement is in the stack  ToArray()ToArray() – converts the stack to an array– converts the stack to an array  TrimExcess()TrimExcess() – sets the capacity to– sets the capacity to the actual number of elementsthe actual number of elements
  • 28.
    Stack<T>Stack<T> – Example–Example  UsingUsing Push()Push(),, Pop()Pop() andand Peek()Peek() methodsmethods static void Main()static void Main() {{ Stack<string> stack = new Stack<string>();Stack<string> stack = new Stack<string>(); stack.Push("1. Ivan");stack.Push("1. Ivan"); stack.Push("2. Nikolay");stack.Push("2. Nikolay"); stack.Push("3. Maria");stack.Push("3. Maria"); stack.Push("4. George");stack.Push("4. George"); Console.WriteLine("Top = {0}", stack.Peek());Console.WriteLine("Top = {0}", stack.Peek()); while (stack.Count > 0)while (stack.Count > 0) {{ string personName = stack.Pop();string personName = stack.Pop(); Console.WriteLine(personName);Console.WriteLine(personName); }} }}
  • 29.
  • 30.
    Matching Brackets –ExampleMatching Brackets – Example  We are given an arithmetical expression withWe are given an arithmetical expression with brackets that can be nestedbrackets that can be nested  Goal: extract all sub-expressions in bracketsGoal: extract all sub-expressions in brackets  Example:Example:  1 + (2 - (2+3) * 4 / (3+1)) * 51 + (2 - (2+3) * 4 / (3+1)) * 5  Result:Result:  (2+3)(2+3) || (3+1)(3+1) || (2 - (2+3) * 4 / (3+1))(2 - (2+3) * 4 / (3+1))  Algorithm:Algorithm:  For each 'For each '((' push its index in a stack' push its index in a stack  For each 'For each '))' pop the corresponding start index' pop the corresponding start index
  • 31.
    Matching Brackets –SolutionMatching Brackets – Solution string expression = "1 + (2 - (2+3) * 4 / (3+1)) * 5";string expression = "1 + (2 - (2+3) * 4 / (3+1)) * 5"; Stack<int> stack = new Stack<int>();Stack<int> stack = new Stack<int>(); for (int index = 0; index < expression.Length; index++)for (int index = 0; index < expression.Length; index++) {{ char ch = expression[index];char ch = expression[index]; if (ch == '(')if (ch == '(') {{ stack.Push(index);stack.Push(index); }} else if (ch == ')')else if (ch == ')') {{ int startIndex = stack.Pop();int startIndex = stack.Pop(); int length = index - startIndex + 1;int length = index - startIndex + 1; string contents =string contents = expression.Substring(startIndex, length);expression.Substring(startIndex, length); Console.WriteLine(contents);Console.WriteLine(contents); }} }}
  • 32.
  • 33.
    QueuesQueues Static and DynamicImplementationStatic and Dynamic Implementation
  • 34.
    The Queue ADTTheQueue ADT  FIFO (First In First Out) structureFIFO (First In First Out) structure  Elements inserted at the tail (Enqueue)Elements inserted at the tail (Enqueue)  Elements removed from the head (Elements removed from the head (DequeueDequeue))  Useful in many situationsUseful in many situations Print queues, message queues, etc.Print queues, message queues, etc.  Can be implemented in several waysCan be implemented in several ways Statically (using array)Statically (using array) Dynamically (using pointers)Dynamically (using pointers) Using theUsing the Queue<T>Queue<T> classclass
  • 35.
    Static QueueStatic Queue Static (array-based) implementationStatic (array-based) implementation Has limited (fixed) capacityHas limited (fixed) capacity Implement as a “circular array”Implement as a “circular array” HasHas headhead andand tailtail indices, pointing to theindices, pointing to the head and the tail of the cyclic queuehead and the tail of the cyclic queue SS 77 1212 22 55 0 1 2 3 4 5 6 7 headhead tailtail
  • 36.
    Linked QueueLinked Queue Dynamic (pointer-based) implementationDynamic (pointer-based) implementation Each item has 2 fields:Each item has 2 fields: valuevalue andand nextnext Dynamically create and delete objectsDynamically create and delete objects 22 nextnext 77 nextnext headhead 44 nextnext 55 nextnext nullnull tailtail
  • 37.
    TheThe Queue<T>Queue<T> ClassClass StandardQueue Implementation in .NETStandard Queue Implementation in .NET
  • 38.
    TheThe Queue<T>Queue<T> ClassClass Implements the queue data structure using aImplements the queue data structure using a circular resizable arraycircular resizable array  Elements are from the same typeElements are from the same type TT  TT can be any type, e.g.can be any type, e.g. Stack<int>Stack<int>  Size is dynamically increased as neededSize is dynamically increased as needed  Basic functionality:Basic functionality:  Enqueue(T)Enqueue(T) – adds an element to the– adds an element to the end of the queueend of the queue  Dequeue()Dequeue() – removes and returns the– removes and returns the element at the beginning of the queueelement at the beginning of the queue
  • 39.
    TheThe Queue<T>Queue<T> Class(2)Class (2)  Basic functionality:Basic functionality:  Peek()Peek() – returns the element at the beginning– returns the element at the beginning of the queue without removing itof the queue without removing it  CountCount – returns the number of elements– returns the number of elements  Clear()Clear() – removes all elements– removes all elements  Contains(T)Contains(T) – determines whether given– determines whether given element is in the queueelement is in the queue  ToArray()ToArray() – converts the queue to an array– converts the queue to an array  TrimExcess()TrimExcess() – sets the capacity to the– sets the capacity to the actual number of elements in the queueactual number of elements in the queue
  • 40.
    Queue<T>Queue<T> –– ExampleExample UsingUsing Enqueue()Enqueue() andand Dequeue()Dequeue() methodsmethods static void Main()static void Main() {{ Queue<string> queue = new Queue<string>();Queue<string> queue = new Queue<string>(); queue.Enqueue("Message One");queue.Enqueue("Message One"); queue.Enqueue("Message Two");queue.Enqueue("Message Two"); queue.Enqueue("Message Three");queue.Enqueue("Message Three"); queue.Enqueue("Message Four");queue.Enqueue("Message Four"); while (queue.Count > 0)while (queue.Count > 0) {{ string message = queue.Dequeue();string message = queue.Dequeue(); Console.WriteLine(message);Console.WriteLine(message); }} }}
  • 41.
  • 42.
     We aregiven the sequence:We are given the sequence: S =S = NN,, N+1N+1,, 2*N2*N,, N+2N+2,, 2*(N+1)2*(N+1),, 2*N+12*N+1,, 4*N4*N,, ……  Find the first index of given number PFind the first index of given number P  Example: N =Example: N = 33, P =, P = 1616 S =S = 33,, 44,, 66,, 55,, 88,, 77,, 1212,, 66,, 1010,, 99,, 1616,, 88,, 1414,, …… Index of P =Index of P = 1111 Sequence N, N+1, 2*NSequence N, N+1, 2*N +1+1 *2*2 +1+1 *2*2 +1+1 *2*2
  • 43.
    Sequence – Solutionwith a QueueSequence – Solution with a Queue int n = 3, p = 16;int n = 3, p = 16; Queue<int> queue = new Queue<int>();Queue<int> queue = new Queue<int>(); queue.Enqueue(n);queue.Enqueue(n); int index = 0;int index = 0; while (queue.Count > 0)while (queue.Count > 0) {{ int current = queue.Dequeue();int current = queue.Dequeue(); index++;index++; if (current == p)if (current == p) {{ Console.WriteLine("Index = {0}", index);Console.WriteLine("Index = {0}", index); return;return; }} queue.Enqueue(current+1);queue.Enqueue(current+1); queue.Enqueue(2*current);queue.Enqueue(2*current); }}
  • 44.
    Sequence N, N+1,2*NSequence N, N+1, 2*N Live DemoLive Demo
  • 45.
  • 46.
    Priority QueuePriority Queue What is aWhat is a PriorityPriority QueueQueue Data type to efficiently support finding the itemData type to efficiently support finding the item with the highest prioritywith the highest priority Basic operationsBasic operations  Enqueue(T element)Enqueue(T element)  DequeueDequeue  There is no build-inThere is no build-in PriorityPriority QueueQueue in .NETin .NET Can be easily implemented usingCan be easily implemented using PowerCollectionsPowerCollections
  • 47.
    Priority Queue ImplementationPriorityQueue Implementation class PriorityQueue<T> where T:IComparable<T>class PriorityQueue<T> where T:IComparable<T> {{ private OrderedBag<T> bag;private OrderedBag<T> bag; publicpublic intint CountCount {{ get { returnget { return bag.Countbag.Count; }; } private set{ }private set{ } }} public PriorityQueue()public PriorityQueue() {{ bag = newbag = new OrderedBag<TOrderedBag<T>();>(); }} public void Enqueue(T element)public void Enqueue(T element) {{ bag.Add(elementbag.Add(element);); }} public T Dequeue()public T Dequeue() {{ var element = bag.GetFirst();var element = bag.GetFirst(); bag.RemoveFirstbag.RemoveFirst();(); return element;return element; }} }} 47 Necessary to provideNecessary to provide comparable elementscomparable elements
  • 48.
    Priority Queue AdditionalPriorityQueue Additional NotesNotes  The generic type is needed to implementThe generic type is needed to implement IComparable<T>IComparable<T>  It is not necessary to useIt is not necessary to use OrderedBagOrderedBag Other Data Structures also can be usedOther Data Structures also can be used  Adding and Removing Element in theAdding and Removing Element in the PriorityPriority QueueQueue is with complexity logNis with complexity logN  Keeps the elements SortedKeeps the elements Sorted Always returns the best element that fulfillsAlways returns the best element that fulfills some conditionsome condition  E.g. the smallest or the biggest elementE.g. the smallest or the biggest element 48
  • 49.
  • 50.
    SummarySummary  ADT aredefined by list of operations independentADT are defined by list of operations independent of their implementationof their implementation  The basic linear data structures in the computerThe basic linear data structures in the computer programming are:programming are:  List (static, linked)List (static, linked)  Implemented by theImplemented by the ListList<T><T> class in .NETclass in .NET  Stack (static, linked)Stack (static, linked)  Implemented by theImplemented by the StackStack<T><T> class in .NETclass in .NET  Queue (static, linked)Queue (static, linked)  Implemented by theImplemented by the QueueQueue<T><T> class in .NETclass in .NET  Priority QueuePriority Queue  Implemented by theImplemented by the OrderedBag<T>OrderedBag<T> classclass
  • 51.
    Linear Data StructuresLinearData Structures Questions?Questions? http://academy.telerik.com
  • 52.
    ExercisesExercises 1.1. Write aprogram that reads from the console aWrite a program that reads from the console a sequence of positive integer numbers. The sequencesequence of positive integer numbers. The sequence ends when empty line is entered. Calculate and printends when empty line is entered. Calculate and print the sum and average of the elements of thethe sum and average of the elements of the sequence. Keep the sequence insequence. Keep the sequence in List<int>List<int>.. 2.2. Write a program that reads N integers from theWrite a program that reads N integers from the console and reverses them using a stack. Use theconsole and reverses them using a stack. Use the Stack<int>Stack<int> class.class. 3.3. Write a program that reads a sequence of integersWrite a program that reads a sequence of integers ((List<int>List<int>) ending with an empty line and sorts) ending with an empty line and sorts them in an increasing order.them in an increasing order.
  • 53.
    Exercises (2)Exercises (2) 4.4.Write a method that finds the longest subsequenceWrite a method that finds the longest subsequence of equal numbers in givenof equal numbers in given List<int>List<int> and returnsand returns the result as newthe result as new List<int>List<int>. Write a program to. Write a program to test whether the method works correctly.test whether the method works correctly. 5.5. Write a program that removes from given sequenceWrite a program that removes from given sequence all negative numbers.all negative numbers. 6.6. Write a program that removes from given sequenceWrite a program that removes from given sequence all numbers that occur odd number of times.all numbers that occur odd number of times. Example:Example: {4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2}{4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2}  {5, 3, 3, 5}{5, 3, 3, 5}
  • 54.
    Exercises (3)Exercises (3) 7.7.Write a program that finds in given array of integersWrite a program that finds in given array of integers (all belonging to the range [0..1000]) how many(all belonging to the range [0..1000]) how many times each of them occurs.times each of them occurs. Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2}Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2} 22  2 times2 times 33  4 times4 times 44  3 times3 times 8.8. * The majorant of an array of size N is a value that* The majorant of an array of size N is a value that occurs in it at least N/2 + 1 times. Write a program tooccurs in it at least N/2 + 1 times. Write a program to find the majorant of given array (if exists). Example:find the majorant of given array (if exists). Example: {2, 2, 3, 3, 2, 3, 4, 3, 3}{2, 2, 3, 3, 2, 3, 4, 3, 3}  33
  • 55.
    Exercises (4)Exercises (4) 9.9.We are given the following sequence:We are given the following sequence: SS11 = N;= N; SS22 = S= S11 + 1;+ 1; SS33 = 2*S= 2*S11 + 1;+ 1; SS44 = S= S11 + 2;+ 2; SS55 = S= S22 + 1;+ 1; SS66 = 2*S= 2*S22 + 1;+ 1; SS77 = S= S22 + 2;+ 2; ...... Using theUsing the Queue<T>Queue<T> class write a program to printclass write a program to print its first 50 members for given N.its first 50 members for given N. Example: N=2Example: N=2  2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...
  • 56.
    Exercises (5)Exercises (5) 10.10.We are given numbers N and M and the followingWe are given numbers N and M and the following operations:operations: a)a) N = N+1N = N+1 b)b) N = N+2N = N+2 c)c) N = N*2N = N*2 Write a program that finds the shortest sequence ofWrite a program that finds the shortest sequence of operations from the list above that starts from N andoperations from the list above that starts from N and finishes in M. Hint: use a queue.finishes in M. Hint: use a queue.  Example: N = 5, M = 16Example: N = 5, M = 16  Sequence: 5Sequence: 5  77  88  1616
  • 57.
    Exercises (6)Exercises (6) 11.11.Write a classWrite a class StudentStudent, that has three fields:, that has three fields: namename (String),(String), ageage(Integer) and(Integer) and paidSemesterOnlinepaidSemesterOnline(Boolean). When in a queue(Boolean). When in a queue the students who paid online are with higherthe students who paid online are with higher priority than those who are about to pay thepriority than those who are about to pay the semester. Write a program which with a givensemester. Write a program which with a given queue of student determine whose turn it is. Hint:queue of student determine whose turn it is. Hint: use priority queueuse priority queue 57
  • 58.
    Exercises (6)Exercises (6) 12.12.Implement the data structureImplement the data structure linked listlinked list. Define a. Define a classclass ListItem<T>ListItem<T> that has two fields:that has two fields: valuevalue (of(of typetype TT) and) and nextItemnextItem (of type(of type ListItem<T>ListItem<T>).). Define additionally a classDefine additionally a class LinkedList<T>LinkedList<T> with awith a single fieldsingle field firstElementfirstElement (of type(of type ListItem<T>ListItem<T>).). 13.13. Implement the ADTImplement the ADT stackstack as auto-resizable array.as auto-resizable array. Resize the capacity on demand (when no space isResize the capacity on demand (when no space is available to add / insert a new element).available to add / insert a new element). 14.14. Implement the ADTImplement the ADT queuequeue as dynamic linked list.as dynamic linked list. Use generics (Use generics (LinkedQueue<T>LinkedQueue<T>) to allow storing) to allow storing different data types in the queue.different data types in the queue.
  • 59.
    Exercises (7)Exercises (7) 15.15.* We are given a labyrinth of size N x N. Some of its* We are given a labyrinth of size N x N. Some of its cells are empty (cells are empty (00) and some are full () and some are full (xx). We can). We can move from an empty cell to another empty cell ifmove from an empty cell to another empty cell if they share common wall. Given a starting positionthey share common wall. Given a starting position ((**) calculate and fill in the array the minimal) calculate and fill in the array the minimal distance from this position to any other cell in thedistance from this position to any other cell in the array. Use "array. Use "uu" for all unreachable cells. Example:" for all unreachable cells. Example: 00 00 00 xx 00 xx 00 xx 00 xx 00 xx 00 ** xx 00 xx 00 00 xx 00 00 00 00 00 00 00 xx xx 00 00 00 00 xx 00 xx 33 44 55 xx uu xx 22 xx 66 xx uu xx 11 ** xx 88 xx 1010 22 xx 66 77 88 99 33 44 55 xx xx 1010 44 55 66 xx uu xx