Select the computational complexity of the stack tolist

Stack Implementation and complexity

From Giphy.com

Stacks are linear collections of elements and are classified as an abstract data type. New elements pile up on prior elements so the top of the stack is always the last element added. The operation that adds an object to the top of stack is called push. Can we remove an element in the middle of the stack immediately? No we cannot. We can only remove an element from the top of the stack. To remove and return an object at the top of the stack, we use the pop operation. There is one more operation to view the object on the top called peek. The last element that is added to the stack is the first element to be removed from it. We call the order of this stack LIFO (Last In, First Out).

Push, Peek, Pop

We can implement stacks by using more concrete data types called Array Lists and/or Linked Lists. They are linear data structures. The difference between them has to do with memory allocation. Array Lists reserve contiguous memory blocks, which generally means much more data is reserved than is needed. For example, if we save 5 numbers in an array list, array list occupy 10 bytes memory instead of 5 bytes one and each memory is neighbor. Linked list do not need contiguous blocks of memory and they need the same amount of memory as amount of data we save. So, they need 5 bytes to save 5 number, but the location of each byte is scattered.

Memory Allocation difference between Array Lists and Linked List

Stack Applications

Parentheses Matching

Many applications of stacks deal with determining whether an input string (or file, or sequence of symbols) is a member of a context-free language. (For a formal introduction to context-free languages (CFLs), take Computer Science 520.) Many programming languages are context free. Also many simpler languages.

As an example, consider the language of balanced parentheses. A sequence of symbols involving ()+* and integers, is said to have balanced-parentheses if each right parenthesis has a corresponding left parenthesis that occurs before it. For example: These expressions have balanced parentheses:

2*7 // no parens - still balanced (1+3) ((2*16)+1)*(44+(17+9)) These expressions do not:(44+38 ) // a right paren with no left (55+(12*11) // missing a )

How do we tell if a sequence of characters represents a balanced-parentheses expression? Use stacks. Idea:

  • Start with an empty stack.
  • For each left parenthesis, push.
  • For each right parenthesis, pop.
  • For each non-parenthesis character, do nothing.
  • The expression is balanced if the stack is empty and there are no more characters to process.
  • It is not balanced if either after the last character the stack is not empty (too many left parens), or if the stack is empty and a right paren is encountered (a right without a left).
(See C++ code to do this in Main & Savitch, p. 312.)

What items do we push onto the stack? If we are just interested in knowing if the expression is balanced, it does not matter. For clarity, we might choose a stack of characters, pushing "(" onto the stack for each left parenthesis.

We can do more. We can match multiple types of delimiters. For example, we might want to match (), [], and {}. In that case we can push the left delimiter onto the stack, and, when we pop, do a check, as in the pseudocode:

if (next character is a right delimiter) then { if (stack is empty) then return false else { pop the stack if (right delimiter is corresponding version of what was popped off the stack) then continue processing else return false } } Other variations on parentheses matching include:
  • valid prefix: return true if the expression is a valid prefix for a balanced parentheses expression, for example "((3+4)+" is a valid prefix. Same idea, but we can return true as long as there is no attempt to pop an empty stack.
  • identifying matches: it is often useful to not only know that an expression is balanced, but to see which pair correspond. For example, in some editors (like Emacs), when you type a right paren the corresponding left paren is momentarily highlighted. Think about how you might adapt a paren matching function to do this.

Memory management issues for stacks

Warning: It is undefined in C++ to copy or assign static arrays. For example,

int a[20]; int b[20]; ... a = b; is implementation dependent. Some compilers may refuse to compile this. Others may take no action. Still others (at least appear to) copy the elements of b to a. Therefore, whenever objects have static array members (as in our static array implementation of stacks), proper copy constructors and assignment operators should be defined to avoid ambiguity. Such a copy constructor and assignment operator for our static array implementation of stacks can be found here.

For stacks with static arrays, we don't need to worry about the destructor. (The array will be destroyed automatically when the object is). Nor need we worry about destoying items that are poppoed off the stack. Consider the code for push and pop:

template void Stack::push(const Item& it) { assert(!isFull()); data[count] = it; count++; } template Item Stack::pop() { assert(!isEmpty()); count--; return(data[count]); } The space occupied by data[count] that is no longer needed after pop returns that item, will be reused by the next assignment (i.e. the next push). Assuming that Item has a properly functioning copy constructor, assignent operator and destructor, thendata[count]=it invokes Item's assignment operator so memory management for the Item is taken care of there. Our documentation states (effectively a precondition for the whole class template) that the "template parameter, Item, is the data type of the items in the Stack. It may be any of the C++ built-in types (int, char, etc.), or a class with a copy constructor, assignment operator, and destructor." Unlike other forms of preconditions, we cannot check this at compile time or run-time. In order for a Stack class to be implemented properly we have to trust that the Item class has been implemented properly as well.

For a stack class template that uses linked lists, we need to write an explicit copy constructor, assignment operator, and destructor because memory is allocated dynamically. However, if we reuse the List template, these become trivial, because all the dynamic memory allocation takes place within that template's implementation (not the stack implementation). The copy constructor, assignment operator, and destructor for stack will automatically call the corresponding member function for the stack's sole member variable, a list.

Scala Stack toList() method with example

In Scala Stack class, the toList() method is utilized to return a list consisting of all the elements of the stack.

Method Definition: def toList: List[A]

Return Type: It returns a list consisting of all the elements of the stack.

Example #1:




// Scala program of toList()

// method

// Import Stack

import scala.collection.mutable._

// Creating object

object GfG

{

// Main method

def main(args:Array[String])

{

// Creating stack

val s1 = Stack(1, 2, 3, 4, 5)

// Print the stack

println(s1)

// Applying toList method

val result = s1.toList

// Display output

print("Elements in the list: ")

for(elem <- result)

print(elem + " ")

}

}

Output: Stack(1, 2, 3, 4, 5) Elements in the list: 1 2 3 4 5

Example #2:




// Scala program of toList()

// method

// Import Stack

import scala.collection.mutable._

// Creating object

object GfG

{

// Main method

def main(args:Array[String])

{

// Creating stack

val s1 = Stack(5, 2, 13, 7, 1)

// Print the stack

println(s1)

// Applying toList method

val result = s1.toList

// Display output

print("Elements in the list: ")

for(elem <- result)

print(elem + " ")

}

}

Output: Stack(5, 2, 13, 7, 1) Elements in the list: 5 2 13 7 1




Article Tags :

Scala

Scala

scala-collection

Scala-Method

Read Full Article

C# | Convert Stack to array

Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.ToArray Method is used to copy a Stack<T> to a new array.

Properties:

  • The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.
  • If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation.
  • Stack accepts null as a valid value and allows duplicate elements.

Syntax:

public T[] ToArray ();

Return Type: This method returns a new array t[] which contains the copy of the elements of the Stack<T>.

Below given are some examples to understand the implementation in a better way :



Example 1:




// C# code to Convert Stack to array

using System;

using System.Collections.Generic;

class GFG {

// Driver code

public static void Main()

{

// Creating a Stack of strings

Stack<string> myStack = new Stack<string>();

// Inserting the elements into the Stack

myStack.Push("Geeks");

myStack.Push("Geeks Classes");

myStack.Push("Noida");

myStack.Push("Data Structures");

myStack.Push("GeeksforGeeks");

// Converting the Stack into array

String[] arr = myStack.ToArray();

// Displaying the elements in array

foreach(string str in arr)

{

Console.WriteLine(str);

}

}

}

Output: GeeksforGeeks Data Structures Noida Geeks Classes Geeks

Example 2:




// C# code to Convert Stack to array

using System;

using System.Collections.Generic;

class GFG {

// Driver code

public static void Main()

{

// Creating a Stack of Integers

Stack<int> myStack = new Stack<int>();

// Inserting the elements into the Stack

myStack.Push(2);

myStack.Push(3);

myStack.Push(4);

myStack.Push(5);

myStack.Push(6);

// Converting the Stack into array

int[] arr = myStack.ToArray();

// Displaying the elements in array

foreach(int i in arr)

{

Console.WriteLine(i);

}

}

}

Output: 6 5 4 3 2

Reference:

  • //docs.microsoft.com/en-us/dotnet/api/system.collections.generic.stack-1.toarray?view=netframework-4.7.2




Article Tags :

C#

CSharp-Generic-Namespace

CSharp-Generic-Stack

CSharp-method

Read Full Article

1. Overview

In this tutorial, we'll talk about the performance of different collections from the Java Collection API. When we talk about collections, we usually think about the List, Map, and Set data structures and their common implementations.

First of all, we'll look at Big-O complexity insights for common operations, and after, we'll show the real numbers of some collection operations running time.

Video liên quan

Postingan terbaru

LIHAT SEMUA