View
53.962
Download
2
Category
Tags:
Preview:
DESCRIPTION
Abstract Data Types Linear Data Structures Static and Linked Lists Generics in C# Lists – the List Class Stacks – the Stack Class Queues – the Queue Class Exercises: Working with Linear Data Types
Citation preview
Linear Data Linear Data StructuresStructures
Lists, Stacks, QueuesLists, Stacks, Queues
Svetlin NakovSvetlin NakovTelerik Telerik
CorporationCorporationwww.telerik.com
Table of ContentsTable of Contents
1.1. Abstract Data Types (ADT)Abstract Data Types (ADT)
2.2. Lists – The Lists – The ListList<T><T> Class Class Static and LinkedStatic and Linked
3.3. Stacks – The Stacks – The Stack<T>Stack<T> Class Class Static and LinkedStatic and Linked
4.4. Queues – The Queues – The Queue<T>Queue<T> Class Class Circular and LinkedCircular and Linked
Priority QueuePriority Queue C# ImplementationC# Implementation
Abstract Data Abstract Data TypesTypes
Basic Data StructuresBasic Data Structures
Abstract Data TypesAbstract Data Types An Abstract Data Type (ADT) is a An Abstract Data Type (ADT) is a
data type together with the data type together with the operations, whose properties are operations, whose properties are specified independently of any specified independently of any particular implementationparticular implementation ADT are set of definitions of ADT are set of definitions of
operations (like the interfaces in C#)operations (like the interfaces in C#) Can have several different Can have several different
implementationsimplementations Different implementations can have Different implementations can have
different efficiencydifferent efficiency
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 Hash tables: use hash functions to search/insertsearch/insert
ListsListsStatic and Dynamic Static and Dynamic ImplementationsImplementations
The List ADTThe List ADT Data structure (container) that Data structure (container) that
containscontainsa sequence of elementsa sequence of elements Can have variable sizeCan have variable size Elements are arranged linearly, in Elements are arranged linearly, in
sequencesequence Can be implemented in several waysCan be implemented in several ways
Statically (using array Statically (using array fixed size) fixed size) Dynamically (linked implementation)Dynamically (linked implementation) Using resizable array (the Using 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 Insertion, deletion and resizing are
slow operationsslow operations
LL 22 1188 77 11
22 33 66 1111 99
0 1 2 3 4 5 6 7
Linked ListLinked List
Dynamic (pointer-based) Dynamic (pointer-based) implementationimplementation
Different formsDifferent forms Singly-linked and doubly-linkedSingly-linked and doubly-linked Sorted and unsortedSorted and unsorted
Singly-linked listSingly-linked list Each Each itemitem has 2 fields: has 2 fields: valuevalue and and nextnext 22
nexnextt
77nexnextt
headhead
44nexnextt
55nexnextt
nullnull
Linked List (2)Linked List (2)
Doubly-linked ListDoubly-linked List Each item has 3 fields: Each item has 3 fields: valuevalue, , nextnext
and and prevprev
22
nextnext
prevprev
headhead
nullnull
77
nextnext
prevprev
nullnull
44
nextnext
prevprev
55
nextnext
prevprev
tailtail
The The ListList<T><T> ClassClassAuto-Resizable Indexed Auto-Resizable Indexed
ListsLists
The The List<T>List<T> Class Class Implements the abstract data Implements the abstract data
structure structure listlist using an array using an array All elements are of the same type All 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 Size is dynamically increased as neededneeded
Basic functionality:Basic functionality: CountCount – returns the number of elements – returns the number of elements Add(T)Add(T) – appends given element at the – appends given element at the
endend
List<T>List<T> – Simple – Simple ExampleExample
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 Inline initialization: initialization: the compiler the compiler
adds specified adds specified elements to elements to
the list.the list.
List<T>List<T> – Simple – Simple ExampleExample
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 – inserts given
element to the list at a specified element to the list at a specified positionposition
Remove(T)Remove(T) – removes the first – removes the first occurrence of given elementoccurrence of given element
RemoveAt(index)RemoveAt(index) – removes the element – removes the element at the specified positionat the specified position
Clear()Clear() – removes all elements – removes all elements Contains(TContains(T)) – determines whether an – determines whether an
element is part of the listelement is part of the list
List<T>List<T> – Functionality – Functionality (2)(2)
IndexOf()IndexOf() – returns the index of the – returns the index of the first occurrence of a valuefirst occurrence of a value in the list in the list ((zero-basedzero-based))
Reverse()Reverse() – reverses the order of the – reverses the order of the elements in the list or a portion of itelements in the list or a portion of it
Sort()Sort() – sorts the elements in the list – sorts the elements in the list or a portion of itor a portion of it
ToArray()ToArray() – converts the elements of – converts the elements of the list to an arraythe list to an array
TrimExcess()TrimExcess() – sets the capacity to – sets the capacity to the actual number of elementsthe actual number of elements
Primes in an Interval – Primes in an Interval – ExampleExample
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); for (int div = 2; div <= Math.Sqrt(num); div++)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 in an an
IntervalIntervalLive DemoLive Demo
Union and Intersection – Union and Intersection – ExampleExample
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 Union and IntersectionIntersection
Live DemoLive Demo
StacksStacksStatic and Dynamic Static and Dynamic ImplementationImplementation
The Stack ADTThe Stack ADT LIFO (Last In First Out) structure LIFO (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 E.g. the execution stack of the program 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 the Using the Stack<T>Stack<T> class class
Static StackStatic Stack Static (array-based) Static (array-based)
implementationimplementation Has limited (fixed) capacityHas limited (fixed) capacity
The current index (The current index (toptop) moves left / ) moves left / right with each pop / pushright with each pop / push
SS 22 1188 77 11
22
0 1 2 3 4 5 6 7
toptop
Linked StackLinked Stack Dynamic (pointer-based) Dynamic (pointer-based)
implementationimplementation Each Each itemitem has 2 fields: has 2 fields: valuevalue and and nextnext
Special pointer keeps the top Special pointer keeps the top elementelement
22nexnextt
77nexnextt
toptop
44nexnextt
55nexnextt
nullnull
The The Stack<T>Stack<T> ClassClassThe Standard Stack The Standard Stack
Implementation in .NETImplementation in .NET
The The Stack<T>Stack<T> Class Class Implements the Implements the stackstack data structure data structure
using an arrayusing an array Elements are from the same type Elements 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 Size is dynamically increased as
neededneeded Basic functionality:Basic functionality:
Push(T)Push(T) – inserts elements to the – inserts elements to the stackstack
Pop()Pop() – removes and returns the top – removes and returns the top element from the stackelement from the stack
The The Stack<T>Stack<T> Class (2) Class (2) Basic functionality:Basic functionality:
Peek()Peek() – returns the top element of the – returns the top element of the stack without removing itstack 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 – determines whether
given element is in the stackgiven element is in the stack ToArray()ToArray() – converts the stack to an – converts the stack to an
arrayarray TrimExcess()TrimExcess() – sets the capacity to – sets the capacity to
the actual number of elements the actual number of elements
Stack<T>Stack<T> – Example – Example
Using Using Push()Push(), , Pop()Pop() and and Peek()Peek() methodsmethodsstatic 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 – Matching Brackets – ExampleExample
We are given an arithmetical expression We are given an arithmetical expression with brackets that can be nestedwith brackets that can be nested
Goal: extract all sub-expressions in Goal: extract all sub-expressions in bracketsbrackets
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 ' pop the corresponding start indexindex
Matching Brackets – Matching Brackets – SolutionSolution
string expression = "1 + (2 - (2+3) * 4 / (3+1)) * string expression = "1 + (2 - (2+3) * 4 / (3+1)) * 5";5";Stack<int> stack = new Stack<int>();Stack<int> stack = new Stack<int>();for (int index = 0; index < expression.Length; for (int index = 0; index < expression.Length; index++)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, expression.Substring(startIndex, length);length); Console.WriteLine(contents);Console.WriteLine(contents); }}}}
Matching Matching BracketsBrackets
Live DemoLive Demo
QueuesQueuesStatic and Dynamic Static and Dynamic ImplementationImplementation
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 the Using the Queue<T>Queue<T> class class
Static QueueStatic Queue Static (array-based) Static (array-based)
implementationimplementation Has limited (fixed) capacityHas limited (fixed) capacity
Implement as a “circular array”Implement as a “circular array”
Has Has headhead and and tailtail indices, pointing indices, pointing to the head and the tail of the cyclic to the head and the tail of the cyclic queuequeue
SS 77 1122 22 55
0 1 2 3 4 5 6 7
headhead tailtail
Linked QueueLinked Queue
Dynamic (pointer-based) Dynamic (pointer-based) implementationimplementation Each item has 2 fields: Each item has 2 fields: valuevalue and and nextnext
Dynamically create and delete Dynamically create and delete objectsobjects
22nexnextt
77nexnextt
headhead
44nexnextt
55nexnextt
nullnull
tailtail
The The Queue<T>Queue<T> ClassClassStandard Queue Implementation Standard Queue Implementation in .NETin .NET
The The Queue<T>Queue<T> Class Class Implements the queue data structure Implements the queue data structure
using a circular resizable arrayusing a circular resizable array Elements are from the same type Elements 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 Size is dynamically increased as
neededneeded Basic functionality:Basic functionality:
Enqueue(T)Enqueue(T) – adds an element to the – adds an element to theend 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
The The Queue<T>Queue<T> Class (2) Class (2) Basic functionality:Basic functionality:
Peek()Peek() – returns the element at the – returns the element at the beginning of the queue without removing beginning of the queue without removing itit
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 – converts the queue to an
arrayarray 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 Using Using Enqueue()Enqueue() and and Dequeue()Dequeue() methods methods
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); }}}}
The The Queue<T>Queue<T> ClassClassLive 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 Sequence – Solution with a Queuea 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, Sequence N, N+1, 2*N2*N
Live DemoLive Demo
Priority Priority QueueQueue
Priority QueuePriority Queue What is a What is a PriorityPriority QueueQueue
Data type to efficiently support Data type to efficiently support finding the item with the highest finding the item with the highest priority priority
Basic operationsBasic operations Enqueue(T element)Enqueue(T element)
DequeueDequeue There is no build-in There is no build-in PriorityPriority QueueQueue
in .NETin .NET Can be easily implemented using Can be easily implemented using PowerCollectionsPowerCollections
Priority Queue Priority Queue ImplementationImplementation
class PriorityQueue<T> where T:IComparable<T>class PriorityQueue<T> where T:IComparable<T>{{ private OrderedBag<T> bag;private OrderedBag<T> bag; public public intint Count Count {{ get { return get { return bag.Countbag.Count; }; } private set{ }private set{ } }} public PriorityQueue()public PriorityQueue() {{ bag = new bag = 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 Necessary to provide provide
comparable comparable elementselements
Priority Queue Priority Queue Additional NotesAdditional Notes
The generic type is needed to The generic type is needed to implement implement IComparable<T>IComparable<T>
It is not necessary to use It is not necessary to use OrderedBagOrderedBag Other Data Structures also can be usedOther Data Structures also can be used
Adding and Removing Element in the Adding and Removing Element in the PriorityPriority QueueQueue is with complexity logN is with complexity logN
Keeps the elements SortedKeeps the elements Sorted Always returns the best element that Always returns the best element that
fulfills some conditionfulfills some condition E.g. the smallest or the biggest elementE.g. the smallest or the biggest element
48
Priority QueuePriority QueueLive DemoLive Demo
49
SummarySummary ADT are defined by list of operations ADT are defined by list of operations
independent of their implementationindependent of their implementation The basic linear data structures in the The basic linear data structures in the
computer programming are:computer programming are: List (static, linked)List (static, linked)
Implemented by the Implemented by the ListList<T><T> class in .NET class in .NET Stack (static, linked)Stack (static, linked)
Implemented by the Implemented by the StackStack<T><T> class in .NET class in .NET Queue (static, linked)Queue (static, linked)
Implemented by the Implemented by the QueueQueue<T><T> class in .NET class in .NET Priority QueuePriority Queue
Implemented by the Implemented by the OrderedBag<T>OrderedBag<T> classclass
Linear Data StructuresLinear Data Structures
Questions?Questions?
http://academy.telerik.com
ExercisesExercises1.1. Write a program that reads from the Write a program that reads from the
console a sequence of positive integer console a sequence of positive integer numbers. The sequence ends when empty numbers. The sequence ends when empty line is entered. Calculate and print the line is entered. Calculate and print the sum and average of the elements of the sum and average of the elements of the sequence. Keep the sequence in sequence. Keep the sequence in List<int>List<int>..
2.2. Write a program that reads N integers Write a program that reads N integers from the console and reverses them using from the console and reverses them using a stack. Use the a stack. Use the Stack<int>Stack<int> class. class.
3.3. Write a program that reads a sequence of Write a program that reads a sequence of integers (integers (List<int>List<int>) ending with an empty ) ending with an empty line and sorts them in an increasing order.line and sorts them in an increasing order.
Exercises (2)Exercises (2)
4.4. Write a method that finds the longest Write a method that finds the longest subsequence of equal numbers in given subsequence of equal numbers in given List<int>List<int> and returns the result as new and returns the result as new List<int>List<int>. Write a program to test . Write a program to test whether the method works correctly.whether the method works correctly.
5.5. Write a program that removes from given Write a program that removes from given sequence all negative numbers.sequence all negative numbers.
6.6. Write a program that removes from given Write a program that removes from given sequence all numbers that occur odd sequence all numbers that occur odd number of times. Example:number of times. 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 Write a program that finds in given array of
integers (all belonging to the range integers (all belonging to the range [0..1000]) how many times each of them [0..1000]) how many times each of them occurs.occurs.
Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2}Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2}
2 2 2 times 2 times
3 3 4 times 4 times
4 4 3 times 3 times
8.8. * The majorant of an array of size N is a * The majorant of an array of size N is a value that occurs in it at least N/2 + 1 times. value that occurs in it at least N/2 + 1 times. Write a program to find the majorant of Write a program to find the majorant of given array (if exists). Example:given array (if exists). Example:
{2, 2, 3, 3, 2, 3, 4, 3, 3} {2, 2, 3, 3, 2, 3, 4, 3, 3} 3 3
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 the Using the Queue<T>Queue<T> class write a program class write a program to print its first 50 members for given N.to print its first 50 members for given N.
Example: N=2 Example: N=2 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6, ...9, 6, ...
Exercises (5)Exercises (5)
10.10.We are given numbers N and M and the We are given numbers N and M and the following operations:following 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 Write a program that finds the shortest sequence of operations from the list sequence of operations from the list above that starts from N and finishes in above that starts from N and finishes in M. Hint: use a queue.M. Hint: use a queue.
Example: N = 5, M = 16Example: N = 5, M = 16
Sequence: 5 Sequence: 5 7 7 8 8 16 16
Exercises (6)Exercises (6)
11.11. Write a class Write a class StudentStudent, that has three , that has three fields: fields: namename (String), (String), ageage(Integer) and (Integer) and paidSemesterOnlinepaidSemesterOnline(Boolean). When in (Boolean). When in a queue the students who paid online a queue the students who paid online are with higher priority than those who are with higher priority than those who are about to pay the semester. Write a are about to pay the semester. Write a program which with a given queue of program which with a given queue of student determine whose turn it is. student determine whose turn it is. Hint: use priority queueHint: use priority queue
57
Exercises (6)Exercises (6)12.12. Implement the data structure Implement the data structure linked listlinked list. .
Define a class Define a class ListItem<T>ListItem<T> that has two fields: that has two fields: valuevalue (of type (of type TT) and ) and nextItemnextItem (of type (of type ListItem<T>ListItem<T>). Define additionally a class ). Define additionally a class LinkedList<T>LinkedList<T> with a single field with a single field firstElementfirstElement (of type (of type ListItem<T>ListItem<T>).).
13.13. Implement the ADT Implement the ADT stackstack as auto-resizable as auto-resizable array. Resize the capacity on demand (when array. Resize the capacity on demand (when no space is available to add / insert a new no space is available to add / insert a new element).element).
14.14. Implement the ADT Implement the ADT queuequeue as dynamic linked as dynamic linked list. Use generics (list. Use generics (LinkedQueue<T>LinkedQueue<T>) to allow ) to allow storing different data types in the queue.storing different data types in the queue.
Exercises (7)Exercises (7)
15.15. * We are given a labyrinth of size N x * We are given a labyrinth of size N x N. Some of its cells are empty (N. Some of its cells are empty (00) and ) and some are full (some are full (xx). We can move from an ). We can move from an empty cell to another empty cell if they empty cell to another empty cell if they share common wall. Given a starting share common wall. Given a starting position (position (**) calculate and fill in the ) calculate and fill in the array the minimal distance from this array the minimal distance from this position to any other cell in the array. position to any other cell in the array. Use "Use "uu" for all unreachable cells. " for all unreachable cells. Example:Example:
00 00 00 xx 00 xx00 xx 00 xx 00 xx00 ** xx 00 xx 0000 xx 00 00 00 0000 00 00 xx xx 0000 00 00 xx 00 xx
33 44 55 xx uu xx22 xx 66 xx uu xx11 ** xx 88 xx 101022 xx 66 77 88 9933 44 55 xx xx 101044 55 66 xx uu xx
Recommended