Lists, Stacks, Queues Svetlin Nakov Telerik Software Academy Manager Technical Trainer

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
NoSQL Concepts, Redis, MongoDB, CouchDB
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Lists, Stacks, Queues Svetlin Nakov Telerik Corporation
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
When and How to Improve Code Performance? Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Creating E/R Diagrams with SQL Server Management Studio and MySQL Workbench Svetlin Nakov Telerik Software Academy Manager Technical.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Arrays, Lists, Stacks, Queues Static and Dynamic Implementation Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Brief Overview of Combinations, Permutations and Binary Vectors Nikolay Kostov Telerik Corporation Technical Trainer.
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Telerik Software Academy End-to-end JavaScript Applications.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
Language enhancements and additions Learning & Development Team Telerik Software Academy.
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Revealing the Secrets of Self-Documenting Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer.
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team Telerik Software Academy.
Data Structures and Algorithms Telerik Software Academy
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Computational Complexity, Choosing Data Structures Svetlin Nakov Telerik Software Academy Manager Technical Trainer
Linear Data Structures: Stacks and Queues
Presentation transcript:

Lists, Stacks, Queues Svetlin Nakov Telerik Software Academy Manager Technical Trainer

1. Abstract Data Types (ADT) 2. Lists – The List Class  Static and Linked 3. Stacks – The Stack Class  Static and Linked 4. Queues – The Queue Class  Circular and Linked  Priority Queue  C# Implementation

Basic Data Structures

 An Abstract Data Type (ADT) is a data type together with the operations, whose properties are specified independently of any particular implementation  ADT are set of definitions of operations (like the interfaces in C#)  Can have several different implementations  Different implementations can have different efficiency

 Linear structures  Lists: fixed size and variable size  Stacks: LIFO (Last In First Out) structure  Queues: FIFO (First In First Out) structure  Trees  Binary, ordered, balanced, etc.  Dictionaries (maps)  Contain pairs (key, value)  Hash tables: use hash functions to search/insert

Static and Dynamic Implementations

 Data structure (container) that contains a sequence of elements  Can have variable size  Elements are arranged linearly, in sequence  Can be implemented in several ways  Statically (using array  fixed size)  Dynamically (linked implementation)  Using resizable array (the List class)

 Implemented by an array  Provides direct access by index  Has fixed capacity  Insertion, deletion and resizing are slow operations L

 Dynamic (pointer-based) implementation  Different forms  Singly-linked and doubly-linked  Sorted and unsorted  Singly-linked list  Each item has 2 fields: value and next 2next7next head4next5next null

 Doubly-linked List  Each item has 3 fields: value, next and prev 2next prev head null7next prev null4next prev5next prev tail

Auto-Resizable Indexed Lists

 Implements the abstract data structure list using an array  All elements are of the same type T  T can be any type, e.g. List, List, List  T can be any type, e.g. List, List, List  Size is dynamically increased as needed  Basic functionality:  Count – returns the number of elements  Add(T) – appends given element at the end

static void Main() { List list = new List () { "C#", "Java" }; List list = new List () { "C#", "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: the compiler adds specified elements to the list.

Live Demo

 list[index] – access element by index  Insert(index, T) – inserts given element to the list at a specified position  Remove(T) – removes the first occurrence of given element  RemoveAt(index) – removes the element at the specified position  Clear() – removes all elements  Contains(T) – determines whether an element is part of the list

 IndexOf() – returns the index of the first occurrence of a value in the list (zero-based)  Reverse() – reverses the order of the elements in the list or a portion of it  Sort() – sorts the elements in the list or a portion of it  ToArray() – converts the elements of the list to an array  TrimExcess() – sets the capacity to the actual number of elements

static List FindPrimes(int start, int end) { List primesList = new List (); List primesList = new List (); 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;}

Live Demo

int[] Union(int[] firstArr, int[] secondArr) { List union = new List (); List union = new List (); 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) { List intersect = new List (); List intersect = new List (); 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();}

Live Demo

Static and Dynamic Implementation

 LIFO (Last In First Out) structure  Elements inserted (push) at “top”  Elements removed (pop) from “top”  Useful in many situations  E.g. the execution stack of the program  Can be implemented in several ways  Statically (using array)  Dynamically (linked implementation)  Using the Stack class

 Static (array-based) implementation  Has limited (fixed) capacity  The current index ( top ) moves left / right with each pop / push S top

 Dynamic (pointer-based) implementation  Each item has 2 fields: value and next  Special pointer keeps the top element 2next7next top4next5next null

The Standard Stack Implementation in.NET

 Implements the stack data structure using an array  Elements are from the same type T  T can be any type, e.g. Stack  T can be any type, e.g. Stack  Size is dynamically increased as needed  Basic functionality:  Push(T) – inserts elements to the stack  Pop() – removes and returns the top element from the stack

 Basic functionality:  Peek() – returns the top element of the stack without removing it  Count – returns the number of elements  Clear() – removes all elements  Contains(T) – determines whether given element is in the stack  ToArray() – converts the stack to an array  TrimExcess() – sets the capacity to the actual number of elements

 Using Push(), Pop() and Peek() methods static void Main() { Stack stack = new Stack (); Stack stack = new Stack (); 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); }}

Live Demo

 We are given an arithmetical expression with brackets that can be nested  Goal: extract all sub-expressions in brackets  Example:  1 + (2 - (2+3) * 4 / (3+1)) * 5  Result:  (2+3) | (3+1) | (2 - (2+3) * 4 / (3+1))  Algorithm:  For each ' ( ' push its index in a stack  For each ' ) ' pop the corresponding start index

string expression = "1 + (2 - (2+3) * 4 / (3+1)) * 5"; Stack stack = new Stack (); 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 = expression.Substring(startIndex, length); string contents = expression.Substring(startIndex, length); Console.WriteLine(contents); Console.WriteLine(contents); }}

Live Demo

Static and Dynamic Implementation

 FIFO (First In First Out) structure  Elements inserted at the tail (Enqueue)  Elements removed from the head (Dequeue)  Useful in many situations  Print queues, message queues, etc.  Can be implemented in several ways  Statically (using array)  Dynamically (using pointers)  Using the Queue class

 Static (array-based) implementation  Has limited (fixed) capacity  Implement as a “circular array”  Has head and tail indices, pointing to the head and the tail of the cyclic queue S headtail

 Dynamic (pointer-based) implementation  Each item has 2 fields: value and next  Dynamically create and delete objects 2next7next head4next5next null tail

Standard Queue Implementation in.NET

 Implements the queue data structure using a circular resizable array  Elements are from the same type T  T can be any type, e.g. Stack  T can be any type, e.g. Stack  Size is dynamically increased as needed  Basic functionality:  Enqueue(T) – adds an element to the end of the queue  Dequeue() – removes and returns the element at the beginning of the queue

 Basic functionality:  Peek() – returns the element at the beginning of the queue without removing it  Count – returns the number of elements  Clear() – removes all elements  Contains(T) – determines whether given element is in the queue  ToArray() – converts the queue to an array  TrimExcess() – sets the capacity to the actual number of elements in the queue

 Using Enqueue() and Dequeue() methods static void Main() { Queue queue = new Queue (); Queue queue = new Queue (); 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); }}

Live Demo

 We are given the sequence: S = N, N+1, 2*N, N+2, 2*(N+1), 2*N+1, 4*N, …  Find the first index of given number P  Example: N = 3, P = 16 S = 3, 4, 6, 5, 8, 7, 12, 6, 10, 9, 16, 8, 14, … Index of P = *2 +1 *2 +1 *2

int n = 3, p = 16; Queue queue = new Queue (); queue.Enqueue(n); int index = 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);}

Live Demo

 What is a Priority Queue  Data type to efficiently support finding the item with the highest priority  The basic operations  Enqueue(T element)  Dequeue  There is no build-in Priority Queue in.NET  Can be easily implemented using PowerCollections

class PriorityQueue where T:IComparable class PriorityQueue where T:IComparable { private OrderedBag bag; private OrderedBag bag; public int Count public int Count { get { return bag.Count; } get { return bag.Count; } private set{ } private set{ } } public PriorityQueue() public PriorityQueue() { bag = new OrderedBag (); bag = new OrderedBag (); } public void Enqueue(T element) public void Enqueue(T element) { bag.Add(element); bag.Add(element); } public T Dequeue() public T Dequeue() { var element = bag.GetFirst(); var element = bag.GetFirst(); bag.RemoveFirst(); bag.RemoveFirst(); return element; return element; }} 47

 The generic type is needed to implement IComparable  The generic type is needed to implement IComparable  It is not necessary to use OrderedBag  Other Data Structures also can be used  Adding and Removing Element in the Priority Queue is with complexity logN  Keeps the elements Sorted  Always returns the best element that fulfills some condition  E.g. the smallest or the biggest element 48

Live Demo 49

 ADT are defined by list of operations independent of their implementation  The basic linear data structures in the computer programming are:  List (static, linked)  Implemented by the List class in.NET  Stack (static, linked)  Implemented by the Stack class in.NET  Queue (static, linked)  Implemented by the Queue class in.NET  Priority Queue  Implemented by the OrderedBag class

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

1. Write a program that reads from the console a sequence of positive integer numbers. The sequence ends when empty line is entered. Calculate and print the sum and average of the elements of the sequence. Keep the sequence in List. 2. Write a program that reads N integers from the console and reverses them using a stack. Use the Stack class. 3. Write a program that reads a sequence of integers ( List ) ending with an empty line and sorts them in an increasing order.

4. Write a method that finds the longest subsequence of equal numbers in given List and returns the result as new List. Write a program to test whether the method works correctly. 5. Write a program that removes from given sequence all negative numbers. 6. Write a program that removes from given sequence all numbers that occur odd number of times. Example: {4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2}  {5, 3, 3, 5}

7. Write a program that finds in given array of integers (all belonging to the range [ ]) how many times each of them occurs. Example: array = {3, 4, 4, 2, 3, 3, 4, 3, 2} 2  2 times 3  4 times 4  3 times 8. * The majorant of an array of size N is a value that occurs in it at least N/2 + 1 times. Write a program to find the majorant of given array (if exists). Example: {2, 2, 3, 3, 2, 3, 4, 3, 3}  3

9. We are given the following sequence: S 1 = N; S 2 = S 1 + 1; S 3 = 2*S 1 + 1; S 4 = S 1 + 2; S 5 = S 2 + 1; S 6 = 2*S 2 + 1; S 7 = S 2 + 2;... Using the Queue class write a program to print its first 50 members for given N. Example: N=2  2, 3, 5, 4, 4, 7, 5, 6, 11, 7, 5, 9, 6,...

10. We are given numbers N and M and the following operations: a)N = N+1 b)N = N+2 c)N = N*2 Write a program that finds the shortest sequence of operations from the list above that starts from N and finishes in M. Hint: use a queue.  Example: N = 5, M = 16  Sequence: 5  7  8  16

11. Implement the data structure linked list. Define a class ListItem that has two fields: value (of type T ) and nextItem (of type ListItem ). Define additionally a class LinkedList with a single field firstElement (of type ListItem ). 12. Implement the ADT stack as auto-resizable array. Resize the capacity on demand (when no space is available to add / insert a new element). 13. Implement the ADT queue as dynamic linked list. Use generics (LinkedQueue ) to allow storing different data types in the queue.

14. * We are given a labyrinth of size N x N. Some of its cells are empty ( 0 ) and some are full ( x ). We can move from an empty cell to another empty cell if they share common wall. Given a starting position ( * ) calculate and fill in the array the minimal distance from this position to any other cell in the array. Use " u " for all unreachable cells. Example: 000x0x0x0x0x 0*x0x0 0x xx0 000x0x345xux2x6xux 1*x8x10 2x xx10 456xux

 Fundamentals of C# Programming Course  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com