SlideShare a Scribd company logo
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

More Related Content

PDF
LectureNotes-06-DSA
PDF
LectureNotes-03-DSA
PPTX
Java - Collections framework
PDF
Collections In Java
PPT
Collections
PDF
07 java collection
PPT
Java Collections Framework
PPT
Queue Data Structure
LectureNotes-06-DSA
LectureNotes-03-DSA
Java - Collections framework
Collections In Java
Collections
07 java collection
Java Collections Framework
Queue Data Structure

What's hot (20)

PPT
Heaps & priority queues
PPT
Collections
PPTX
Collections in .net technology (2160711)
PDF
Is there a perfect data-parallel programming language? (Experiments with More...
PDF
Collections Java e Google Collections
PPT
Collections in Java
PPT
Java collection
PPT
Chapter 11 ds
PPTX
Ist year Msc,2nd sem module1
PPT
PPTX
Presentation on Elementary data structures
PPT
Algorithm: priority queue
PPTX
Collections lecture 35 40
PDF
Aj unit2 notesjavadatastructures
PPTX
Stack Data structure
PDF
LectureNotes-05-DSA
PPTX
Collections - Lists & sets
PPT
Priority queues and heap sorting
PDF
Java Collections Tutorials
ODP
Java 1.5 - whats new and modern patterns (2007)
Heaps & priority queues
Collections
Collections in .net technology (2160711)
Is there a perfect data-parallel programming language? (Experiments with More...
Collections Java e Google Collections
Collections in Java
Java collection
Chapter 11 ds
Ist year Msc,2nd sem module1
Presentation on Elementary data structures
Algorithm: priority queue
Collections lecture 35 40
Aj unit2 notesjavadatastructures
Stack Data structure
LectureNotes-05-DSA
Collections - Lists & sets
Priority queues and heap sorting
Java Collections Tutorials
Java 1.5 - whats new and modern patterns (2007)
Ad

Viewers also liked (12)

PPTX
Data Structures - Lecture 6 [queues]
PPT
7 stacksqueues
PPT
Fallsem2015 16 cp1699-20-jul-2015_rm01_stacks_and_queues
PPT
Lec8
PPTX
Linked stacks and queues
PPT
02 Arrays And Memory Mapping
PDF
Queues
PPT
Introductiont To Aray,Tree,Stack, Queue
PPTX
Data structures
PPTX
queue & its applications
PPTX
Binomial Heaps and Fibonacci Heaps
PDF
Preparation Data Structures 08 queues
Data Structures - Lecture 6 [queues]
7 stacksqueues
Fallsem2015 16 cp1699-20-jul-2015_rm01_stacks_and_queues
Lec8
Linked stacks and queues
02 Arrays And Memory Mapping
Queues
Introductiont To Aray,Tree,Stack, Queue
Data structures
queue & its applications
Binomial Heaps and Fibonacci Heaps
Preparation Data Structures 08 queues
Ad

Similar to 16 Linear data structures (20)

PPT
Basic data-structures-v.1.1
PPTX
Data -structures for class 12 , easy ppt
PPTX
16. Arrays Lists Stacks Queues
PDF
Data-structures7 class xii ashdshd hfuidshfkjhjsa ioh
PPTX
A singly linked list is a linear data structure
PPT
introduction to stack data structures chapter 1
PPT
MODULE 01-INTRODUCTION TO STACK-PRESENTATION
ODP
C++ STL 概觀
PPTX
TSAT Presentation1.pptx
PPT
introduction stacks in data structures and algorithms
PPT
An Introduction to Stack Data Structures
PPTX
Data structures in c#
PPT
01-intro_stacks.ppt
PPT
1 list datastructures
PPT
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
PPT
Intro ds
PPT
9781439035665 ppt ch09
PPT
1597380885789.ppt
PPTX
DS_PPT.pptx
PPTX
Java Generics
Basic data-structures-v.1.1
Data -structures for class 12 , easy ppt
16. Arrays Lists Stacks Queues
Data-structures7 class xii ashdshd hfuidshfkjhjsa ioh
A singly linked list is a linear data structure
introduction to stack data structures chapter 1
MODULE 01-INTRODUCTION TO STACK-PRESENTATION
C++ STL 概觀
TSAT Presentation1.pptx
introduction stacks in data structures and algorithms
An Introduction to Stack Data Structures
Data structures in c#
01-intro_stacks.ppt
1 list datastructures
DATA STRUCTURE AND ALGORITJM POWERPOINT.ppt
Intro ds
9781439035665 ppt ch09
1597380885789.ppt
DS_PPT.pptx
Java Generics

More from maznabili (20)

PPT
22 Methodology of problem solving
PPT
21 High-quality programming code construction part-ii
PPT
21 high-quality programming code construction part-i
PPT
20 Object-oriented programming principles
PPT
19 Algorithms and complexity
PPT
18 Hash tables and sets
PPT
17 Trees and graphs
PPT
15 Text files
PPT
14 Defining classes
PPT
13 Strings and text processing
PPT
12 Exceptions handling
PPT
11 Using classes and objects
PPT
10 Recursion
PPT
09 Methods
PPT
08 Numeral systems
PPT
07 Arrays
PPT
06 Loops
PPT
05 Conditional statements
PPT
04 Console input output-
PPT
03 Operators and expressions
22 Methodology of problem solving
21 High-quality programming code construction part-ii
21 high-quality programming code construction part-i
20 Object-oriented programming principles
19 Algorithms and complexity
18 Hash tables and sets
17 Trees and graphs
15 Text files
14 Defining classes
13 Strings and text processing
12 Exceptions handling
11 Using classes and objects
10 Recursion
09 Methods
08 Numeral systems
07 Arrays
06 Loops
05 Conditional statements
04 Console input output-
03 Operators and expressions

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Cloud computing and distributed systems.
PPTX
Big Data Technologies - Introduction.pptx
PDF
Approach and Philosophy of On baking technology
PDF
Electronic commerce courselecture one. Pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Spectroscopy.pptx food analysis technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Cloud computing and distributed systems.
Big Data Technologies - Introduction.pptx
Approach and Philosophy of On baking technology
Electronic commerce courselecture one. Pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Unlocking AI with Model Context Protocol (MCP)
MIND Revenue Release Quarter 2 2025 Press Release
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Spectral efficient network and resource selection model in 5G networks
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Machine learning based COVID-19 study performance prediction
Spectroscopy.pptx food analysis technology

16 Linear data structures

  • 1. Linear Data StructuresLinear Data Structures Lists, Stacks, QueuesLists, Stacks, Queues Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2. 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
  • 3. Abstract DataTypesAbstract DataTypes Basic Data StructuresBasic Data Structures
  • 4. 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
  • 5. 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
  • 6. ListsLists Static and DynamicStatic and Dynamic ImplementationsImplementations
  • 7. 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)
  • 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)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
  • 11. TheThe ListList<T><T> ClassClass Auto-Resizable Indexed 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> – 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.
  • 14. List<T>List<T> – Simple Example– 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 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; }}
  • 18. PrimesPrimes in anin an 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 IntersectionUnion and Intersection Live DemoLive Demo
  • 21. StacksStacks Static and Dynamic ImplementationStatic and Dynamic Implementation
  • 22. 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
  • 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 The Standard 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); }} }}
  • 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); }} }}
  • 33. QueuesQueues Static and Dynamic ImplementationStatic and Dynamic Implementation
  • 34. 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
  • 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 Standard Queue 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); }} }}
  • 42.  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
  • 43. 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); }}
  • 44. Sequence N, N+1, 2*NSequence N, N+1, 2*N Live DemoLive Demo
  • 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 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
  • 48. 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
  • 50. 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
  • 51. Linear Data StructuresLinear Data Structures Questions?Questions? http://academy.telerik.com
  • 52. 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.
  • 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