Steki gerçəkləşdirin#5087

Steki gerçəkləşdirin (Həll təhlili)

Problemi stekin işini modelləşdirməkdir.

Nümunə

Birinci nümunədə steklə aparılan əməliyyatları nəzərdən keçirək:

Alqoritmin realizasiyası

İşci stek elan edək.

stack<int> s;

Əməliyyatların sayını oxuyaq.

scanf("%d", &n);

Ard-arda əməliyyatı işləyirik.

for (int i = 0; i < n; i++)
{
  scanf("%d", &op);

Elementin daxil edilməsi, push əməliyyatı.

  if (op == 1)
  {
    scanf("%d", &x);
    s.push(x);
  }

Elementin çıxarılması, pop əməliyyatı.

  else
  {
    printf("%d\n", s.top());
    s.pop();
  }
}

Java realizasiyası

import java.util.*;

public class Main
{
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    Stack<Integer> s = new Stack<Integer>();      
    int n = con.nextInt();
    for (int i = 0; i < n; i++)
    {
      int op = con.nextInt();
      if (op == 1)
      {
        int x = con.nextInt();
        s.push(x);
      }
      else
        System.out.println(s.pop());    	  
    }
    con.close();
  }
}   

Java realizasiyası — MyStack sinfi

import java.util.*;

class MyStack
{
  private Vector<Integer> v;
  
  MyStack()
  {
    v = new Vector<Integer>();
  }
  
  public void push(int x)
  {
    v.add(x);
  }
  
  public int pop()
  {
    int last = v.lastElement();
    v.remove(v.size() - 1);
    return last;
  }  
}

public class Main
{
  public static void main(String[] args)
  {
    Scanner con = new Scanner(System.in);
    MyStack s = new MyStack();      
    int n = con.nextInt();
    for (int i = 0; i < n; i++)
    {
      int op = con.nextInt();
      if (op == 1)
      {
        int x = con.nextInt();
        s.push(x);
      }
      else
        System.out.println(s.pop());    	  
    }
    con.close();
  }
}   

Python realizasiyası

Əməliyyatların sayını oxuyaq.

n = int(input())

siyahısını stek modelləşdirmək üçün istifadə edəcəyik.

stack = []

Ard-arda əməliyyatı işləyirik.

for i in range(n):
  lst = list(map(int,input().split()))

Elementin daxil edilməsi, push əməliyyatı.

  if (lst[0] == 1):
    stack.append(lst[1])

Elementin çıxarılması, pop əməliyyatı.

  else:
    print(stack.pop())