Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 44.65 KB | None | 0 0
  1. getMinimum()
  2.  
  3. Real stack Min stack
  4.  
  5. 5 --> TOP 1
  6. 1 1
  7. 4 2
  8. 6 2
  9. 2 2
  10.  
  11. Real stack Min stack
  12.  
  13. 4 2
  14. 6 2
  15. 2 2
  16.  
  17. Real stack Min stack
  18.  
  19. 1 --> TOP 1
  20. 5 1
  21. 1 2
  22. 4
  23. 6
  24. 2
  25.  
  26. Real stack Min stack
  27.  
  28. 5 --> TOP 1
  29. 1 2
  30. 4
  31. 6
  32. 2
  33.  
  34. Real stack Min stack
  35.  
  36. 1 1
  37. 4 2
  38. 6
  39. 2
  40.  
  41. Real stack Min stack
  42.  
  43. 4 2
  44. 6
  45. 2
  46.  
  47. using System.Collections.Generic;
  48.  
  49. public class FastMinStack<T>
  50. {
  51. private readonly Stack<T> stack = new Stack<T>();
  52. // Could pass this in to the constructor
  53. private readonly IComparer<T> comparer = Comparer<T>.Default;
  54.  
  55. private T currentMin;
  56.  
  57. public T Minimum
  58. {
  59. get { return currentMin; }
  60. }
  61.  
  62. public void Push(T element)
  63. {
  64. if (stack.Count == 0 ||
  65. comparer.Compare(element, currentMin) <= 0)
  66. {
  67. stack.Push(currentMin);
  68. stack.Push(element);
  69. currentMin = element;
  70. }
  71. else
  72. {
  73. stack.Push(element);
  74. }
  75. }
  76.  
  77. public T Pop()
  78. {
  79. T ret = stack.Pop();
  80. if (comparer.Compare(ret, currentMin) == 0)
  81. {
  82. currentMin = stack.Pop();
  83. }
  84. return ret;
  85. }
  86. }
  87.  
  88. public sealed class MinStack {
  89. private int MinimumValue;
  90. private readonly Stack<int> Stack = new Stack<int>();
  91.  
  92. public int GetMinimum() {
  93. if (IsEmpty) {
  94. throw new InvalidOperationException("Stack is empty");
  95. }
  96. return MinimumValue;
  97. }
  98.  
  99. public int Pop() {
  100. var value = Stack.Pop();
  101. if (value == MinimumValue) {
  102. MinimumValue = Stack.Min();
  103. }
  104. return value;
  105. }
  106.  
  107. public void Push(int value) {
  108. if (IsEmpty || value < MinimumValue) {
  109. MinimumValue = value;
  110. }
  111. Stack.Push(value);
  112. }
  113.  
  114. private bool IsEmpty { get { return Stack.Count() == 0; } }
  115. }
  116.  
  117. public class StackWithMin {
  118. int min;
  119. int size;
  120. int[] data = new int[1024];
  121.  
  122. public void push ( int val ) {
  123. if ( size == 0 ) {
  124. data[size] = val;
  125. min = val;
  126. } else if ( val < min) {
  127. data[size] = 2 * val - min;
  128. min = val;
  129.  
  130. assert (data[size] < min);
  131. } else {
  132. data[size] = val;
  133. }
  134.  
  135. ++size;
  136.  
  137. // check size and grow array
  138. }
  139.  
  140. public int getMin () {
  141. return min;
  142. }
  143.  
  144. public int pop () {
  145. --size;
  146.  
  147. int val = data[size];
  148.  
  149. if ( ( size > 0 ) && ( val < min ) ) {
  150. int prevMin = min;
  151. min += min - val;
  152. return prevMin;
  153. } else {
  154. return val;
  155. }
  156. }
  157.  
  158. public boolean isEmpty () {
  159. return size == 0;
  160. }
  161.  
  162. public static void main (String...args) {
  163. StackWithMin stack = new StackWithMin();
  164.  
  165. for ( String arg: args )
  166. stack.push( Integer.parseInt( arg ) );
  167.  
  168. while ( ! stack.isEmpty() ) {
  169. int min = stack.getMin();
  170. int val = stack.pop();
  171.  
  172. System.out.println( val + " " + min );
  173. }
  174.  
  175. System.out.println();
  176. }
  177.  
  178. }
  179.  
  180. public class LinkedStackWithMin {
  181. private static class Link {
  182. final int value;
  183. final Link next;
  184.  
  185. Link ( int value, Link next ) {
  186. this.value = value;
  187. this.next = next;
  188. }
  189.  
  190. int pop ( LinkedStackWithMin stack ) {
  191. stack.top = next;
  192. return value;
  193. }
  194. }
  195.  
  196. private static class MinLink extends Link {
  197. MinLink ( int value, Link next ) {
  198. super( value, next );
  199. }
  200.  
  201. int pop ( LinkedStackWithMin stack ) {
  202. stack.top = next;
  203. int prevMin = stack.min;
  204. stack.min = value;
  205. return prevMin;
  206. }
  207. }
  208.  
  209. Link top;
  210. int min;
  211.  
  212. public LinkedStackWithMin () {
  213. }
  214.  
  215. public void push ( int val ) {
  216. if ( ( top == null ) || ( val < min ) ) {
  217. top = new MinLink(min, top);
  218. min = val;
  219. } else {
  220. top = new Link(val, top);
  221. }
  222. }
  223.  
  224. public int pop () {
  225. return top.pop(this);
  226. }
  227.  
  228. public int getMin () {
  229. return min;
  230. }
  231.  
  232. public boolean isEmpty () {
  233. return top == null;
  234. }
  235.  
  236. typedef struct _stack_link stack_with_min;
  237.  
  238. typedef struct _stack_link stack_link;
  239.  
  240. struct _stack_link {
  241. size_t next;
  242. int value;
  243. };
  244.  
  245. stack_link* get_next ( stack_link* link )
  246. {
  247. return ( stack_link * )( link -> next & ~ ( size_t ) 1 );
  248. }
  249.  
  250. bool is_min ( stack_link* link )
  251. {
  252. return ( link -> next & 1 ) ! = 0;
  253. }
  254.  
  255. void push ( stack_with_min* stack, int value )
  256. {
  257. stack_link *link = malloc ( sizeof( stack_link ) );
  258.  
  259. link -> next = ( size_t ) stack -> next;
  260.  
  261. if ( (stack -> next == 0) || ( value == stack -> value ) ) {
  262. link -> value = stack -> value;
  263. link -> next |= 1; // mark as min
  264. } else {
  265. link -> value = value;
  266. }
  267.  
  268. stack -> next = link;
  269. }
  270.  
  271. etc.;
  272.  
  273. public class MinStack {
  274. long min;
  275. Stack<Long> stack;
  276.  
  277. public MinStack(){
  278. stack = new Stack<>();
  279. }
  280.  
  281. public void push(int x) {
  282. if (stack.isEmpty()) {
  283. stack.push(0L);
  284. min = x;
  285. } else {
  286. stack.push(x - min); //Could be negative if min value needs to change
  287. if (x < min) min = x;
  288. }
  289. }
  290.  
  291. public int pop() {
  292. if (stack.isEmpty()) return;
  293.  
  294. long pop = stack.pop();
  295.  
  296. if (pop < 0) {
  297. long ret = min
  298. min = min - pop; //If negative, increase the min value
  299. return (int)ret;
  300. }
  301. return (int)(pop + min);
  302.  
  303. }
  304.  
  305. public int top() {
  306. long top = stack.peek();
  307. if (top < 0) {
  308. return (int)min;
  309. } else {
  310. return (int)(top + min);
  311. }
  312. }
  313.  
  314. public int getMin() {
  315. return (int)min;
  316. }
  317. }
  318.  
  319. class StackDemo
  320. {
  321. int[] stk = new int[100];
  322. int top;
  323. public StackDemo()
  324. {
  325. top = -1;
  326. }
  327. public void Push(int value)
  328. {
  329. if (top == 100)
  330. Console.WriteLine("Stack Overflow");
  331. else
  332. stk[++top] = value;
  333. }
  334. public bool IsEmpty()
  335. {
  336. if (top == -1)
  337. return true;
  338. else
  339. return false;
  340. }
  341. public int Pop()
  342. {
  343. if (IsEmpty())
  344. {
  345. Console.WriteLine("Stack Underflow");
  346. return 0;
  347. }
  348. else
  349. return stk[top--];
  350. }
  351. public void Display()
  352. {
  353. for (int i = top; i >= 0; i--)
  354. Console.WriteLine(stk[i]);
  355. }
  356. }
  357. class MinStack : StackDemo
  358. {
  359. int top;
  360. int[] stack = new int[100];
  361. StackDemo s1; int min;
  362. public MinStack()
  363. {
  364. top = -1;
  365. s1 = new StackDemo();
  366. }
  367. public void PushElement(int value)
  368. {
  369. s1.Push(value);
  370. if (top == 100)
  371. Console.WriteLine("Stack Overflow");
  372. if (top == -1)
  373. {
  374. stack[++top] = value;
  375. stack[++top] = value;
  376. }
  377. else
  378. {
  379. // stack[++top]=value;
  380. int ele = PopElement();
  381. stack[++top] = ele;
  382. int a = MininmumElement(min, value);
  383. stack[++top] = min;
  384.  
  385. stack[++top] = value;
  386. stack[++top] = a;
  387.  
  388.  
  389. }
  390. }
  391. public int PopElement()
  392. {
  393.  
  394. if (top == -1)
  395. return 1000;
  396. else
  397. {
  398. min = stack[top--];
  399. return stack[top--];
  400. }
  401.  
  402. }
  403. public int PopfromStack()
  404. {
  405. if (top == -1)
  406. return 1000;
  407. else
  408. {
  409. s1.Pop();
  410. return PopElement();
  411. }
  412. }
  413. public int MininmumElement(int a,int b)
  414. {
  415. if (a > b)
  416. return b;
  417. else
  418. return a;
  419. }
  420. public int StackTop()
  421. {
  422. return stack[top];
  423. }
  424. public void DisplayMinStack()
  425. {
  426. for (int i = top; i >= 0; i--)
  427. Console.WriteLine(stack[i]);
  428. }
  429. }
  430. class Program
  431. {
  432. static void Main(string[] args)
  433. {
  434. MinStack ms = new MinStack();
  435. ms.PushElement(15);
  436. ms.PushElement(2);
  437. ms.PushElement(1);
  438. ms.PushElement(13);
  439. ms.PushElement(5);
  440. ms.PushElement(21);
  441. Console.WriteLine("Min Stack");
  442. ms.DisplayMinStack();
  443. Console.WriteLine("Minimum Element:"+ms.StackTop());
  444. ms.PopfromStack();
  445. ms.PopfromStack();
  446. ms.PopfromStack();
  447. ms.PopfromStack();
  448.  
  449. Console.WriteLine("Min Stack");
  450. ms.DisplayMinStack();
  451. Console.WriteLine("Minimum Element:" + ms.StackTop());
  452. Thread.Sleep(1000000);
  453. }
  454. }
  455.  
  456. //
  457. // main.cpp
  458. // Eighth
  459. //
  460. // Created by chaitanya on 4/11/13.
  461. // Copyright (c) 2013 cbilgika. All rights reserved.
  462. //
  463.  
  464. #include <iostream>
  465. #include <limits>
  466. using namespace std;
  467. struct stack
  468. {
  469. int num;
  470. int minnum;
  471. }a[100];
  472.  
  473. void push(int n,int m,int &top)
  474. {
  475.  
  476. top++;
  477. if (top>=100) {
  478. cout<<"Stack Full";
  479. cout<<endl;
  480. }
  481. else{
  482. a[top].num = n;
  483. a[top].minnum = m;
  484. }
  485.  
  486.  
  487. }
  488.  
  489. void pop(int &top)
  490. {
  491. if (top<0) {
  492. cout<<"Stack Empty";
  493. cout<<endl;
  494. }
  495. else{
  496. top--;
  497. }
  498.  
  499.  
  500. }
  501. void print(int &top)
  502. {
  503. cout<<"Stack: "<<endl;
  504. for (int j = 0; j<=top ; j++) {
  505. cout<<"("<<a[j].num<<","<<a[j].minnum<<")"<<endl;
  506. }
  507. }
  508.  
  509.  
  510. void get_min(int &top)
  511. {
  512. if (top < 0)
  513. {
  514. cout<<"Empty Stack";
  515. }
  516. else{
  517. cout<<"Minimum element is: "<<a[top].minnum;
  518. }
  519. cout<<endl;
  520. }
  521.  
  522. int main()
  523. {
  524.  
  525. int top = -1,min = numeric_limits<int>::min(),num;
  526. cout<<"Enter the list to push (-1 to stop): ";
  527. cin>>num;
  528. while (num!=-1) {
  529. if (top == -1) {
  530. min = num;
  531. push(num, min, top);
  532. }
  533. else{
  534. if (num < min) {
  535. min = num;
  536. }
  537. push(num, min, top);
  538. }
  539. cin>>num;
  540. }
  541. print(top);
  542. get_min(top);
  543. return 0;
  544. }
  545.  
  546. Enter the list to push (-1 to stop): 5
  547. 1
  548. 4
  549. 6
  550. 2
  551. -1
  552. Stack:
  553. (5,5)
  554. (1,1)
  555. (4,1)
  556. (6,1)
  557. (2,1)
  558. Minimum element is: 1
  559.  
  560. package com.java.util.collection.advance.datastructure;
  561.  
  562. /**
  563. *
  564. * @author vsinha
  565. *
  566. */
  567. public abstract interface Stack<E> {
  568.  
  569. /**
  570. * Placing a data item on the top of the stack is called pushing it
  571. * @param element
  572. *
  573. */
  574. public abstract void push(E element);
  575.  
  576.  
  577. /**
  578. * Removing it from the top of the stack is called popping it
  579. * @return the top element
  580. */
  581. public abstract E pop();
  582.  
  583. /**
  584. * Get it top element from the stack and it
  585. * but the item is not removed from the stack, which remains unchanged
  586. * @return the top element
  587. */
  588. public abstract E peek();
  589.  
  590. /**
  591. * Get the current size of the stack.
  592. * @return
  593. */
  594. public abstract int size();
  595.  
  596.  
  597. /**
  598. * Check whether stack is empty of not.
  599. * @return true if stack is empty, false if stack is not empty
  600. */
  601. public abstract boolean empty();
  602.  
  603.  
  604.  
  605. }
  606.  
  607.  
  608.  
  609. package com.java.util.collection.advance.datastructure;
  610.  
  611. @SuppressWarnings("hiding")
  612. public abstract interface MinMaxStack<Integer> extends Stack<Integer> {
  613.  
  614. public abstract int min();
  615.  
  616. public abstract int max();
  617.  
  618. }
  619.  
  620.  
  621. package com.java.util.collection.advance.datastructure;
  622.  
  623. import java.util.Arrays;
  624.  
  625. /**
  626. *
  627. * @author vsinha
  628. *
  629. * @param <E>
  630. */
  631. public class MyStack<E> implements Stack<E> {
  632.  
  633. private E[] elements =null;
  634. private int size = 0;
  635. private int top = -1;
  636. private final static int DEFAULT_INTIAL_CAPACITY = 10;
  637.  
  638.  
  639. public MyStack(){
  640. // If you don't specify the size of stack. By default, Stack size will be 10
  641. this(DEFAULT_INTIAL_CAPACITY);
  642. }
  643.  
  644. @SuppressWarnings("unchecked")
  645. public MyStack(int intialCapacity){
  646. if(intialCapacity <=0){
  647. throw new IllegalArgumentException("initial capacity can't be negative or zero");
  648. }
  649. // Can't create generic type array
  650. elements =(E[]) new Object[intialCapacity];
  651. }
  652.  
  653. @Override
  654. public void push(E element) {
  655. ensureCapacity();
  656. elements[++top] = element;
  657. ++size;
  658. }
  659.  
  660. @Override
  661. public E pop() {
  662. E element = null;
  663. if(!empty()) {
  664. element=elements[top];
  665. // Nullify the reference
  666. elements[top] =null;
  667. --top;
  668. --size;
  669. }
  670. return element;
  671. }
  672.  
  673. @Override
  674. public E peek() {
  675. E element = null;
  676. if(!empty()) {
  677. element=elements[top];
  678. }
  679. return element;
  680. }
  681.  
  682. @Override
  683. public int size() {
  684. return size;
  685. }
  686.  
  687. @Override
  688. public boolean empty() {
  689. return size == 0;
  690. }
  691.  
  692. /**
  693. * Increases the capacity of this <tt>Stack by double of its current length</tt> instance,
  694. * if stack is full
  695. */
  696. private void ensureCapacity() {
  697. if(size != elements.length) {
  698. // Don't do anything. Stack has space.
  699. } else{
  700. elements = Arrays.copyOf(elements, size *2);
  701. }
  702. }
  703.  
  704. @Override
  705. public String toString() {
  706. return "MyStack [elements=" + Arrays.toString(elements) + ", size="
  707. + size + ", top=" + top + "]";
  708. }
  709.  
  710.  
  711. }
  712.  
  713.  
  714. package com.java.util.collection.advance.datastructure;
  715.  
  716. /**
  717. * Time complexity will be O(1) to find min and max in a given stack.
  718. * @author vsinha
  719. *
  720. */
  721. public class MinMaxStackFinder extends MyStack<Integer> implements MinMaxStack<Integer> {
  722.  
  723. private MyStack<Integer> minStack;
  724.  
  725. private MyStack<Integer> maxStack;
  726.  
  727. public MinMaxStackFinder (int intialCapacity){
  728. super(intialCapacity);
  729. minStack =new MyStack<Integer>();
  730. maxStack =new MyStack<Integer>();
  731.  
  732. }
  733. public void push(Integer element) {
  734. // Current element is lesser or equal than min() value, Push the current element in min stack also.
  735. if(!minStack.empty()) {
  736. if(min() >= element) {
  737. minStack.push(element);
  738. }
  739. } else{
  740. minStack.push(element);
  741. }
  742. // Current element is greater or equal than max() value, Push the current element in max stack also.
  743. if(!maxStack.empty()) {
  744. if(max() <= element) {
  745. maxStack.push(element);
  746. }
  747. } else{
  748. maxStack.push(element);
  749. }
  750. super.push(element);
  751. }
  752.  
  753.  
  754. public Integer pop(){
  755. Integer curr = super.pop();
  756. if(curr !=null) {
  757. if(min() == curr) {
  758. minStack.pop();
  759. }
  760.  
  761. if(max() == curr){
  762. maxStack.pop();
  763. }
  764. }
  765. return curr;
  766. }
  767.  
  768.  
  769. @Override
  770. public int min() {
  771. return minStack.peek();
  772. }
  773.  
  774. @Override
  775. public int max() {
  776. return maxStack.peek();
  777. }
  778.  
  779.  
  780. @Override
  781. public String toString() {
  782. return super.toString()+"nMinMaxStackFinder [minStack=" + minStack + "n maxStack="
  783. + maxStack + "]" ;
  784. }
  785.  
  786.  
  787.  
  788.  
  789. }
  790.  
  791. // You can use the below program to execute it.
  792.  
  793. package com.java.util.collection.advance.datastructure;
  794.  
  795. import java.util.Random;
  796.  
  797. public class MinMaxStackFinderApp {
  798.  
  799. public static void main(String[] args) {
  800. MinMaxStack<Integer> stack =new MinMaxStackFinder(10);
  801. Random random =new Random();
  802. for(int i =0; i< 10; i++){
  803. stack.push(random.nextInt(100));
  804. }
  805. System.out.println(stack);
  806. System.out.println("MAX :"+stack.max());
  807. System.out.println("MIN :"+stack.min());
  808.  
  809. stack.pop();
  810. stack.pop();
  811. stack.pop();
  812. stack.pop();
  813. stack.pop();
  814.  
  815. System.out.println(stack);
  816. System.out.println("MAX :"+stack.max());
  817. System.out.println("MIN :"+stack.min());
  818. }
  819. }
  820.  
  821. private final LinkedList<E> mainStack = new LinkedList<E>();
  822. private final LinkedList<E> minStack = new LinkedList<E>();
  823. private final Comparator<E> comparator;
  824.  
  825. public MinStack(Comparator<E> comparator)
  826. {
  827. this.comparator = comparator;
  828. }
  829.  
  830. /**
  831. * Pushes an element onto the stack.
  832. *
  833. *
  834. * @param e the element to push
  835. */
  836. public void push(E e) {
  837. mainStack.push(e);
  838. if(minStack.isEmpty())
  839. {
  840. minStack.push(e);
  841. }
  842. else if(comparator.compare(e, minStack.peek())<=0)
  843. {
  844. minStack.push(e);
  845. }
  846. else
  847. {
  848. minStack.push(minStack.peek());
  849. }
  850. }
  851.  
  852. /**
  853. * Pops an element from the stack.
  854. *
  855. *
  856. * @throws NoSuchElementException if this stack is empty
  857. */
  858. public E pop() {
  859. minStack.pop();
  860. return mainStack.pop();
  861. }
  862.  
  863. /**
  864. * Returns but not remove smallest element from the stack. Return null if stack is empty.
  865. *
  866. */
  867. public E getMinimum()
  868. {
  869. return minStack.peek();
  870. }
  871.  
  872. @Override
  873. public String toString() {
  874. StringBuilder sb = new StringBuilder();
  875. sb.append("Main stack{");
  876. for (E e : mainStack) {
  877. sb.append(e.toString()).append(",");
  878. }
  879. sb.append("}");
  880.  
  881. sb.append(" Min stack{");
  882. for (E e : minStack) {
  883. sb.append(e.toString()).append(",");
  884. }
  885. sb.append("}");
  886.  
  887. sb.append(" Minimum = ").append(getMinimum());
  888. return sb.toString();
  889. }
  890.  
  891. public static void main(String[] args) {
  892. MinStack<Integer> st = new MinStack<Integer>(Comparators.INTEGERS);
  893.  
  894. st.push(2);
  895. Assert.assertTrue("2 is min in stack {2}", st.getMinimum().equals(2));
  896. System.out.println(st);
  897.  
  898. st.push(6);
  899. Assert.assertTrue("2 is min in stack {2,6}", st.getMinimum().equals(2));
  900. System.out.println(st);
  901.  
  902. st.push(4);
  903. Assert.assertTrue("2 is min in stack {2,6,4}", st.getMinimum().equals(2));
  904. System.out.println(st);
  905.  
  906. st.push(1);
  907. Assert.assertTrue("1 is min in stack {2,6,4,1}", st.getMinimum().equals(1));
  908. System.out.println(st);
  909.  
  910. st.push(5);
  911. Assert.assertTrue("1 is min in stack {2,6,4,1,5}", st.getMinimum().equals(1));
  912. System.out.println(st);
  913.  
  914. st.pop();
  915. Assert.assertTrue("1 is min in stack {2,6,4,1}", st.getMinimum().equals(1));
  916. System.out.println(st);
  917.  
  918. st.pop();
  919. Assert.assertTrue("2 is min in stack {2,6,4}", st.getMinimum().equals(2));
  920. System.out.println(st);
  921.  
  922. st.pop();
  923. Assert.assertTrue("2 is min in stack {2,6}", st.getMinimum().equals(2));
  924. System.out.println(st);
  925.  
  926. st.pop();
  927. Assert.assertTrue("2 is min in stack {2}", st.getMinimum().equals(2));
  928. System.out.println(st);
  929.  
  930. st.pop();
  931. Assert.assertTrue("null is min in stack {}", st.getMinimum()==null);
  932. System.out.println(st);
  933. }
  934.  
  935. private final LinkedList<E> mainStack = new LinkedList<E>();
  936. private final LinkedList<E> minStack = new LinkedList<E>();
  937. private final Comparator<E> comparator;
  938.  
  939. public MinStack(Comparator<E> comparator)
  940. {
  941. this.comparator = comparator;
  942. }
  943.  
  944. /**
  945. * Pushes an element onto the stack.
  946. *
  947. *
  948. * @param e the element to push
  949. */
  950. public void push(E e) {
  951. mainStack.push(e);
  952. if(minStack.isEmpty())
  953. {
  954. minStack.push(e);
  955. }
  956. else if(comparator.compare(e, minStack.peek())<=0)
  957. {
  958. minStack.push(e);
  959. }
  960. else
  961. {
  962. minStack.push(minStack.peek());
  963. }
  964. }
  965.  
  966. /**
  967. * Pops an element from the stack.
  968. *
  969. *
  970. * @throws NoSuchElementException if this stack is empty
  971. */
  972. public E pop() {
  973. minStack.pop();
  974. return mainStack.pop();
  975. }
  976.  
  977. /**
  978. * Returns but not remove smallest element from the stack. Return null if stack is empty.
  979. *
  980. */
  981. public E getMinimum()
  982. {
  983. return minStack.peek();
  984. }
  985.  
  986. @Override
  987. public String toString() {
  988. StringBuilder sb = new StringBuilder();
  989. sb.append("Main stack{");
  990. for (E e : mainStack) {
  991. sb.append(e.toString()).append(",");
  992. }
  993. sb.append("}");
  994.  
  995. sb.append(" Min stack{");
  996. for (E e : minStack) {
  997. sb.append(e.toString()).append(",");
  998. }
  999. sb.append("}");
  1000.  
  1001. sb.append(" Minimum = ").append(getMinimum());
  1002. return sb.toString();
  1003. }
  1004.  
  1005. public static void main(String[] args) {
  1006. MinStack<Integer> st = new MinStack<Integer>(Comparators.INTEGERS);
  1007.  
  1008. st.push(2);
  1009. Assert.assertTrue("2 is min in stack {2}", st.getMinimum().equals(2));
  1010. System.out.println(st);
  1011.  
  1012. st.push(6);
  1013. Assert.assertTrue("2 is min in stack {2,6}", st.getMinimum().equals(2));
  1014. System.out.println(st);
  1015.  
  1016. st.push(4);
  1017. Assert.assertTrue("2 is min in stack {2,6,4}", st.getMinimum().equals(2));
  1018. System.out.println(st);
  1019.  
  1020. st.push(1);
  1021. Assert.assertTrue("1 is min in stack {2,6,4,1}", st.getMinimum().equals(1));
  1022. System.out.println(st);
  1023.  
  1024. st.push(5);
  1025. Assert.assertTrue("1 is min in stack {2,6,4,1,5}", st.getMinimum().equals(1));
  1026. System.out.println(st);
  1027.  
  1028. st.pop();
  1029. Assert.assertTrue("1 is min in stack {2,6,4,1}", st.getMinimum().equals(1));
  1030. System.out.println(st);
  1031.  
  1032. st.pop();
  1033. Assert.assertTrue("2 is min in stack {2,6,4}", st.getMinimum().equals(2));
  1034. System.out.println(st);
  1035.  
  1036. st.pop();
  1037. Assert.assertTrue("2 is min in stack {2,6}", st.getMinimum().equals(2));
  1038. System.out.println(st);
  1039.  
  1040. st.pop();
  1041. Assert.assertTrue("2 is min in stack {2}", st.getMinimum().equals(2));
  1042. System.out.println(st);
  1043.  
  1044. st.pop();
  1045. Assert.assertTrue("null is min in stack {}", st.getMinimum()==null);
  1046. System.out.println(st);
  1047. }
  1048.  
  1049. #include<stdio.h>
  1050. struct stack
  1051. {
  1052. int data;
  1053. int mindata;
  1054. }a[100];
  1055.  
  1056. void push(int *tos,int input)
  1057. {
  1058. if (*tos > 100)
  1059. {
  1060. printf("overflow");
  1061. return;
  1062. }
  1063. (*tos)++;
  1064. a[(*tos)].data=input;
  1065. if (0 == *tos)
  1066. a[*tos].mindata=input;
  1067. else if (a[*tos -1].mindata < input)
  1068. a[*tos].mindata=a[*tos -1].mindata;
  1069. else
  1070. a[*tos].mindata=input;
  1071. }
  1072.  
  1073. int pop(int * tos)
  1074. {
  1075. if (*tos <= -1)
  1076. {
  1077. printf("underflow");
  1078. return -1;
  1079. }
  1080. return(a[(*tos)--].data);
  1081. }
  1082. void display(int tos)
  1083. {
  1084. while (tos > -1)
  1085. {
  1086. printf("%d:%dt",a[tos].data,a[tos].mindata);
  1087. tos--;
  1088. }
  1089. }
  1090.  
  1091. int min(int tos)
  1092. {
  1093. return(a[tos].mindata);
  1094. }
  1095. int main()
  1096. {
  1097. int tos=-1,x,choice;
  1098. while(1)
  1099. {
  1100. printf("press 1-push,2-pop,3-mindata,4-display,5-exit ");
  1101. scanf("%d",&choice);
  1102. switch(choice)
  1103. {
  1104. case 1: printf("enter data to push");
  1105. scanf("%d",&x);
  1106. push(&tos,x);
  1107. break;
  1108. case 2: printf("the poped out data=%d ",pop(&tos));
  1109. break;
  1110. case 3: printf("The min peeped data:%d",min(tos));
  1111. break;
  1112. case 4: printf("The elements of stack n");
  1113. display(tos);
  1114. break;
  1115. default: exit(0);
  1116. }
  1117. }
  1118.  
  1119. struct StackGetMin {
  1120. void push(int x) {
  1121. elements.push(x);
  1122. if (minStack.empty() || x <= minStack.top())
  1123. minStack.push(x);
  1124. }
  1125. bool pop() {
  1126. if (elements.empty()) return false;
  1127. if (elements.top() == minStack.top())
  1128. minStack.pop();
  1129. elements.pop();
  1130. return true;
  1131. }
  1132. bool getMin(int &min) {
  1133. if (minStack.empty()) {
  1134. return false;
  1135. } else {
  1136. min = minStack.top();
  1137. return true;
  1138. }
  1139. }
  1140. stack<int> elements;
  1141. stack<int> minStack;
  1142. };
  1143.  
  1144. struct Node {
  1145. let data: Int
  1146. init(_ d:Int){
  1147. data = d
  1148. }
  1149. }
  1150.  
  1151. struct Stack {
  1152. private var backingStore = [Node]()
  1153. private var minArray = [Int]()
  1154.  
  1155. mutating func push(n:Node) {
  1156. backingStore.append(n)
  1157. minArray.append(n.data)
  1158. minArray.sort(>)
  1159. minArray
  1160. }
  1161.  
  1162. mutating func pop() -> Node? {
  1163. if(backingStore.isEmpty){
  1164. return nil
  1165. }
  1166.  
  1167. let n = backingStore.removeLast()
  1168.  
  1169. var found = false
  1170. minArray = minArray.filter{
  1171. if (!found && $0 == n.data) {
  1172. found = true
  1173. return false
  1174. }
  1175. return true
  1176. }
  1177. return n
  1178. }
  1179.  
  1180. func min() -> Int? {
  1181. return minArray.last
  1182. }
  1183. }
  1184.  
  1185. class MyStackImplementation{
  1186. private final int capacity = 4;
  1187. int min;
  1188. int arr[] = new int[capacity];
  1189. int top = -1;
  1190.  
  1191. public void push ( int val ) {
  1192. top++;
  1193. if(top <= capacity-1){
  1194. if(top == 0){
  1195. min = val;
  1196. arr[top] = val;
  1197. }
  1198. else if(val < min){
  1199. arr[top] = arr[top]+min;
  1200. min = arr[top]-min;
  1201. arr[top] = arr[top]-min;
  1202. }
  1203. else {
  1204. arr[top] = val;
  1205. }
  1206. System.out.println("element is pushed");
  1207. }
  1208. else System.out.println("stack is full");
  1209.  
  1210. }
  1211.  
  1212. public void pop () {
  1213. top--;
  1214. if(top > -1){
  1215.  
  1216. min = arr[top];
  1217. }
  1218. else {min=0; System.out.println("stack is under flow");}
  1219.  
  1220. }
  1221. public int min(){
  1222. return min;
  1223. }
  1224.  
  1225. public boolean isEmpty () {
  1226. return top == 0;
  1227. }
  1228.  
  1229. public static void main(String...s){
  1230. MyStackImplementation msi = new MyStackImplementation();
  1231. msi.push(1);
  1232. msi.push(4);
  1233. msi.push(2);
  1234. msi.push(10);
  1235. System.out.println(msi.min);
  1236. msi.pop();
  1237. msi.pop();
  1238. msi.pop();
  1239. msi.pop();
  1240. msi.pop();
  1241. System.out.println(msi.min);
  1242.  
  1243. }
  1244. }
  1245.  
  1246. class FastStack {
  1247.  
  1248. private static class StackNode {
  1249. private Integer data;
  1250. private StackNode nextMin;
  1251.  
  1252. public StackNode(Integer data) {
  1253. this.data = data;
  1254. }
  1255.  
  1256. public Integer getData() {
  1257. return data;
  1258. }
  1259.  
  1260. public void setData(Integer data) {
  1261. this.data = data;
  1262. }
  1263.  
  1264. public StackNode getNextMin() {
  1265. return nextMin;
  1266. }
  1267.  
  1268. public void setNextMin(StackNode nextMin) {
  1269. this.nextMin = nextMin;
  1270. }
  1271.  
  1272. }
  1273.  
  1274. private LinkedList<StackNode> stack = new LinkedList<>();
  1275.  
  1276. private StackNode currentMin = null;
  1277.  
  1278. public void push(Integer item) {
  1279. StackNode node = new StackNode(item);
  1280. if (currentMin == null) {
  1281. currentMin = node;
  1282. node.setNextMin(null);
  1283. } else if (item < currentMin.getData()) {
  1284. StackNode oldMinNode = currentMin;
  1285. node.setNextMin(oldMinNode);
  1286. currentMin = node;
  1287. }
  1288.  
  1289. stack.addFirst(node);
  1290. }
  1291.  
  1292. public Integer pop() {
  1293. if (stack.isEmpty()) {
  1294. throw new EmptyStackException();
  1295. }
  1296. StackNode node = stack.peek();
  1297. if (currentMin == node) {
  1298. currentMin = node.getNextMin();
  1299. }
  1300. stack.removeFirst();
  1301. return node.getData();
  1302. }
  1303.  
  1304. public Integer getMinimum() {
  1305. if (stack.isEmpty()) {
  1306. throw new NoSuchElementException("Stack is empty");
  1307. }
  1308. return currentMin.getData();
  1309. }
  1310. }
  1311.  
  1312. vector<pair<int,int> >A;
  1313. int sz=0; // to keep track of the size of vector
  1314.  
  1315. class MinStack
  1316. {
  1317. public:
  1318. MinStack()
  1319. {
  1320. A.clear();
  1321. sz=0;
  1322. }
  1323.  
  1324. void push(int x)
  1325. {
  1326. int mn=(sz==0)?x: min(A[sz-1].second,x); //find the minimum value upto this pushed value
  1327. A.push_back(make_pair(x,mn));
  1328. sz++; // increment the size
  1329. }
  1330.  
  1331. void pop()
  1332. {
  1333. if(sz==0) return;
  1334. A.pop_back(); // pop the last inserted element
  1335. sz--; // decrement size
  1336. }
  1337.  
  1338. int top()
  1339. {
  1340. if(sz==0) return -1; // if stack empty return -1
  1341. return A[sz-1].first; // return the top element
  1342. }
  1343.  
  1344. int getMin()
  1345. {
  1346. if(sz==0) return -1;
  1347. return A[sz-1].second; // return the minimum value at sz-1
  1348. }
  1349. };
  1350.  
  1351. **The task can be acheived by creating two stacks:**
  1352.  
  1353.  
  1354.  
  1355. import java.util.Stack;
  1356. /*
  1357. *
  1358. * Find min in stack using O(n) Space Complexity
  1359. */
  1360. public class DeleteMinFromStack {
  1361.  
  1362. void createStack(Stack<Integer> primary, Stack<Integer> minStack, int[] arr) {
  1363. /* Create main Stack and in parallel create the stack which contains the minimum seen so far while creating main Stack */
  1364. primary.push(arr[0]);
  1365. minStack.push(arr[0]);
  1366.  
  1367. for (int i = 1; i < arr.length; i++) {
  1368. primary.push(arr[i]);
  1369. if (arr[i] <= minStack.peek())// Condition to check to push the value in minimum stack only when this urrent value is less than value seen at top of this stack */
  1370. minStack.push(arr[i]);
  1371. }
  1372.  
  1373. }
  1374.  
  1375. int findMin(Stack<Integer> secStack) {
  1376. return secStack.peek();
  1377. }
  1378.  
  1379. public static void main(String args[]) {
  1380.  
  1381. Stack<Integer> primaryStack = new Stack<Integer>();
  1382. Stack<Integer> minStack = new Stack<Integer>();
  1383.  
  1384. DeleteMinFromStack deleteMinFromStack = new DeleteMinFromStack();
  1385.  
  1386. int[] arr = { 5, 5, 6, 8, 13, 1, 11, 6, 12 };
  1387. deleteMinFromStack.createStack(primaryStack, minStack, arr);
  1388. int mimElement = deleteMinFromStack.findMin(primaryStack, minStack);
  1389. /** This check for algorithm when the main Stack Shrinks by size say i as in loop below */
  1390. for (int i = 0; i < 2; i++) {
  1391. primaryStack.pop();
  1392. }
  1393.  
  1394. System.out.println(" Minimum element is " + mimElement);
  1395. }
  1396.  
  1397. }
  1398. /*
  1399. here in have tried to add for loop wherin the main tack can be shrinked/expaned so we can check the algorithm */
  1400.  
  1401. The Code for same is below:
  1402.  
  1403.  
  1404. package com.practical;
  1405.  
  1406. import java.util.Collections;
  1407. import java.util.Iterator;
  1408. import java.util.LinkedList;
  1409. import java.util.List;
  1410. import java.util.Stack;
  1411.  
  1412. public class CognitaStack {
  1413.  
  1414. public School findMin(Stack<School> stack, Stack<School> minStack) {
  1415.  
  1416. if (!stack.empty() && !minStack.isEmpty())
  1417. return (School) minStack.peek();
  1418. return null;
  1419. }
  1420.  
  1421. public School removeSchool(Stack<School> stack, Stack<School> minStack) {
  1422.  
  1423. if (stack.isEmpty())
  1424. return null;
  1425. School temp = stack.peek();
  1426. if (temp != null) {
  1427. // if(temp.compare(stack.peek(), minStack.peek())<0){
  1428. stack.pop();
  1429. minStack.pop();
  1430. // }
  1431.  
  1432. // stack.pop();
  1433. }
  1434. return stack.peek();
  1435. }
  1436.  
  1437. public static void main(String args[]) {
  1438.  
  1439. Stack<School> stack = new Stack<School>();
  1440. Stack<School> minStack = new Stack<School>();
  1441.  
  1442. List<School> lst = new LinkedList<School>();
  1443.  
  1444. School s1 = new School("Polam School", "London", 3);
  1445. School s2 = new School("AKELEY WOOD SENIOR SCHOOL", "BUCKINGHAM", 4);
  1446. School s3 = new School("QUINTON HOUSE SCHOOL", "NORTHAMPTON", 2);
  1447. School s4 = new School("OAKLEIGH HOUSE SCHOOL", " SWANSEA", 5);
  1448. School s5 = new School("OAKLEIGH-OAK HIGH SCHOOL", "Devon", 1);
  1449. School s6 = new School("BritishInter2", "Devon", 7);
  1450.  
  1451. lst.add(s1);
  1452. lst.add(s2);
  1453. lst.add(s3);
  1454. lst.add(s4);
  1455. lst.add(s5);
  1456. lst.add(s6);
  1457.  
  1458. Iterator<School> itr = lst.iterator();
  1459. while (itr.hasNext()) {
  1460. School temp = itr.next();
  1461. if ((minStack.isEmpty()) || (temp.compare(temp, minStack.peek()) < 0)) { // minStack.peek().equals(temp)
  1462. stack.push(temp);
  1463. minStack.push(temp);
  1464. } else {
  1465. minStack.push(minStack.peek());
  1466. stack.push(temp);
  1467. }
  1468.  
  1469. }
  1470.  
  1471. CognitaStack cogStack = new CognitaStack();
  1472. System.out.println(" Minimum in Stack is " + cogStack.findMin(stack, minStack).name);
  1473. cogStack.removeSchool(stack, minStack);
  1474. cogStack.removeSchool(stack, minStack);
  1475.  
  1476. System.out.println(" Minimum in Stack is "
  1477. + ((cogStack.findMin(stack, minStack) != null) ? cogStack.findMin(stack, minStack).name : "Empty"));
  1478. }
  1479.  
  1480. }
  1481.  
  1482. package com.practical;
  1483.  
  1484. import java.util.Comparator;
  1485.  
  1486. public class School implements Comparator<School> {
  1487.  
  1488. String name;
  1489. String location;
  1490. int rank;
  1491.  
  1492. public School(String name, String location, int rank) {
  1493. super();
  1494. this.name = name;
  1495. this.location = location;
  1496. this.rank = rank;
  1497. }
  1498.  
  1499. @Override
  1500. public int hashCode() {
  1501. final int prime = 31;
  1502. int result = 1;
  1503. result = prime * result + ((location == null) ? 0 : location.hashCode());
  1504. result = prime * result + ((name == null) ? 0 : name.hashCode());
  1505. result = prime * result + rank;
  1506. return result;
  1507. }
  1508.  
  1509. @Override
  1510. public boolean equals(Object obj) {
  1511. if (this == obj)
  1512. return true;
  1513. if (obj == null)
  1514. return false;
  1515. if (getClass() != obj.getClass())
  1516. return false;
  1517. School other = (School) obj;
  1518. if (location == null) {
  1519. if (other.location != null)
  1520. return false;
  1521. } else if (!location.equals(other.location))
  1522. return false;
  1523. if (name == null) {
  1524. if (other.name != null)
  1525. return false;
  1526. } else if (!name.equals(other.name))
  1527. return false;
  1528. if (rank != other.rank)
  1529. return false;
  1530. return true;
  1531. }
  1532.  
  1533. public String getName() {
  1534. return name;
  1535. }
  1536.  
  1537. public void setName(String name) {
  1538. this.name = name;
  1539. }
  1540.  
  1541. public String getLocation() {
  1542. return location;
  1543. }
  1544.  
  1545. public void setLocation(String location) {
  1546. this.location = location;
  1547. }
  1548.  
  1549. public int getRank() {
  1550. return rank;
  1551. }
  1552.  
  1553. public void setRank(int rank) {
  1554. this.rank = rank;
  1555. }
  1556.  
  1557. public int compare(School o1, School o2) {
  1558. // TODO Auto-generated method stub
  1559. return o1.rank - o2.rank;
  1560. }
  1561.  
  1562. }
  1563.  
  1564. class SchoolComparator implements Comparator<School> {
  1565.  
  1566. public int compare(School o1, School o2) {
  1567. return o1.rank - o2.rank;
  1568. }
  1569.  
  1570. }
  1571.  
  1572. class Stack {
  1573. private:
  1574. struct stack_node {
  1575. int val;
  1576. stack_node *next;
  1577. };
  1578. stack_node *top;
  1579. stack_node *min_top;
  1580. public:
  1581. Stack() {
  1582. top = nullptr;
  1583. min_top = nullptr;
  1584. }
  1585. void push(int num) {
  1586. stack_node *new_node = nullptr;
  1587. new_node = new stack_node;
  1588. new_node->val = num;
  1589.  
  1590. if (is_empty()) {
  1591. top = new_node;
  1592. new_node->next = nullptr;
  1593.  
  1594. min_top = new_node;
  1595. new_node->next = nullptr;
  1596. } else {
  1597. new_node->next = top;
  1598. top = new_node;
  1599.  
  1600. if (new_node->val <= min_top->val) {
  1601. new_node->next = min_top;
  1602. min_top = new_node;
  1603. }
  1604. }
  1605. }
  1606.  
  1607. void pop(int &num) {
  1608. stack_node *tmp_node = nullptr;
  1609. stack_node *min_tmp = nullptr;
  1610.  
  1611. if (is_empty()) {
  1612. std::cout << "It's emptyn";
  1613. } else {
  1614. num = top->val;
  1615. if (top->val == min_top->val) {
  1616. min_tmp = min_top->next;
  1617. delete min_top;
  1618. min_top = min_tmp;
  1619. }
  1620. tmp_node = top->next;
  1621. delete top;
  1622. top = tmp_node;
  1623. }
  1624. }
  1625.  
  1626. bool is_empty() const {
  1627. return !top;
  1628. }
  1629.  
  1630. void get_min(int &item) {
  1631. item = min_top->val;
  1632. }
  1633. };
  1634.  
  1635. int main() {
  1636. int pop, min_el;
  1637. Stack my_stack;
  1638.  
  1639. my_stack.push(4);
  1640. my_stack.push(6);
  1641. my_stack.push(88);
  1642. my_stack.push(1);
  1643. my_stack.push(234);
  1644. my_stack.push(2);
  1645.  
  1646. my_stack.get_min(min_el);
  1647. cout << "Min: " << min_el << endl;
  1648.  
  1649. my_stack.pop(pop);
  1650. cout << "Popped stock element: " << pop << endl;
  1651.  
  1652. my_stack.pop(pop);
  1653. cout << "Popped stock element: " << pop << endl;
  1654.  
  1655. my_stack.pop(pop);
  1656. cout << "Popped stock element: " << pop << endl;
  1657.  
  1658. my_stack.get_min(min_el);
  1659. cout << "Min: " << min_el << endl;
  1660.  
  1661. return 0;
  1662. }
  1663.  
  1664. Min: 1
  1665. Popped stock element: 2
  1666. Popped stock element: 234
  1667. Popped stock element: 1
  1668. Min: 4
  1669.  
  1670. class MinStackOptimized:
  1671. def __init__(self):
  1672. self.stack = []
  1673. self.min = None
  1674.  
  1675. def push(self, x):
  1676. if not self.stack:
  1677. # stack is empty therefore directly add
  1678. self.stack.append(x)
  1679. self.min = x
  1680. else:
  1681. """
  1682. Directly add (x-self.min) to the stack. This also ensures anytime we have a
  1683. negative number on the stack is when x was less than existing minimum
  1684. recorded thus far.
  1685. """
  1686. self.stack.append(x-self.min)
  1687. if x < self.min:
  1688. # Update x to new min
  1689. self.min = x
  1690.  
  1691. def pop(self):
  1692. x = self.stack.pop()
  1693. if x < 0:
  1694. """
  1695. if popped element was negative therefore this was the minimum
  1696. element, whose actual value is in self.min but stored value is what
  1697. contributes to get the next min. (this is one of the trick we use to ensure
  1698. we are able to get old minimum once current minimum gets popped proof is given
  1699. below in pop method), value stored during push was:
  1700. (x - self.old_min) and self.min = x therefore we need to backtrack
  1701. these steps self.min(current) - stack_value(x) actually implies to
  1702. x (self.min) - (x - self.old_min)
  1703. which therefore gives old_min back and therefore can now be set
  1704. back as current self.min.
  1705. """
  1706. self.min = self.min - x
  1707.  
  1708. def top(self):
  1709. x = self.stack[-1]
  1710. if x < 0:
  1711. """
  1712. As discussed above anytime there is a negative value on stack, this
  1713. is the min value so far and therefore actual value is in self.min,
  1714. current stack value is just for getting the next min at the time
  1715. this gets popped.
  1716. """
  1717. return self.min
  1718. else:
  1719. """
  1720. if top element of the stack was positive then it's simple, it was
  1721. not the minimum at the time of pushing it and therefore what we did
  1722. was x(actual) - self.min(min element at current stage) let's say `y`
  1723. therefore we just need to reverse the process to get the actual
  1724. value. Therefore self.min + y, which would translate to
  1725. self.min + x(actual) - self.min, thereby giving x(actual) back
  1726. as desired.
  1727. """
  1728. return x + self.min
  1729.  
  1730. def getMin(self):
  1731. # Always self.min variable holds the minimum so for so easy peezy.
  1732. return self.min
  1733.  
  1734. public class StackWithMin extends Stack<Integer> {
  1735.  
  1736. private Stack<Integer> min;
  1737.  
  1738. public StackWithMin() {
  1739. min = new Stack<>();
  1740. }
  1741.  
  1742. public void push(int num) {
  1743. if (super.isEmpty()) {
  1744. min.push(num);
  1745. } else if (num <= min.peek()) {
  1746. min.push(num);
  1747. }
  1748. super.push(num);
  1749. }
  1750.  
  1751. public int min() {
  1752. return min.peek();
  1753. }
  1754.  
  1755. public Integer pop() {
  1756. if (super.peek() == min.peek()) {
  1757. min.pop();
  1758. }
  1759. return super.pop();
  1760. }
  1761. }
  1762.  
  1763. public class Stack {
  1764.  
  1765. int[] elements;
  1766. int top;
  1767. Linkedlists min;
  1768.  
  1769. public Stack(int n) {
  1770. elements = new int[n];
  1771. top = 0;
  1772. min = new Linkedlists();
  1773. }
  1774.  
  1775. public void realloc(int n) {
  1776. int[] tab = new int[n];
  1777. for (int i = 0; i < top; i++) {
  1778. tab[i] = elements[i];
  1779. }
  1780.  
  1781. elements = tab;
  1782. }
  1783.  
  1784. public void push(int x) {
  1785. if (top == elements.length) {
  1786. realloc(elements.length * 2);
  1787. }
  1788. if (top == 0) {
  1789. min.pre(x);
  1790. } else if (x < min.head.data) {
  1791. min.pre(x);
  1792. } else {
  1793. min.app(x);
  1794. }
  1795. elements[top++] = x;
  1796. }
  1797.  
  1798. public int pop() {
  1799.  
  1800. int x = elements[--top];
  1801. if (top == 0) {
  1802.  
  1803. }
  1804. if (this.getMin() == x) {
  1805. min.head = min.head.next;
  1806. }
  1807. elements[top] = 0;
  1808. if (4 * top < elements.length) {
  1809. realloc((elements.length + 1) / 2);
  1810. }
  1811.  
  1812. return x;
  1813. }
  1814.  
  1815. public void display() {
  1816. for (Object x : elements) {
  1817. System.out.print(x + " ");
  1818. }
  1819.  
  1820. }
  1821.  
  1822. public int getMin() {
  1823. if (top == 0) {
  1824. return 0;
  1825. }
  1826. return this.min.head.data;
  1827. }
  1828.  
  1829. public static void main(String[] args) {
  1830. Stack stack = new Stack(4);
  1831. stack.push(2);
  1832. stack.push(3);
  1833. stack.push(1);
  1834. stack.push(4);
  1835. stack.push(5);
  1836. stack.pop();
  1837. stack.pop();
  1838. stack.pop();
  1839. stack.push(1);
  1840. stack.pop();
  1841. stack.pop();
  1842. stack.pop();
  1843. stack.push(2);
  1844. System.out.println(stack.getMin());
  1845. stack.display();
  1846.  
  1847. }
  1848.  
  1849. }
  1850.  
  1851. class Stack{
  1852. int min;
  1853. Node top;
  1854. static class Node{
  1855. private int data;
  1856. private Node next;
  1857. private int min;
  1858.  
  1859. Node(int data, int min){
  1860. this.data = data;
  1861. this.min = min;
  1862. this.next = null;
  1863. }
  1864. }
  1865.  
  1866. void push(int data){
  1867. Node temp;
  1868. if(top == null){
  1869. temp = new Node(data,data);
  1870. top = temp;
  1871. top.min = data;
  1872. }
  1873. if(top.min > data){
  1874. temp = new Node(data,data);
  1875. temp.next = top;
  1876. top = temp;
  1877. } else {
  1878. temp = new Node(data, top.min);
  1879. temp.next = top;
  1880. top = temp;
  1881. }
  1882. }
  1883.  
  1884. void pop(){
  1885. if(top != null){
  1886. top = top.next;
  1887. }
  1888. }
  1889.  
  1890. int min(){
  1891. return top.min;
  1892. }
  1893.  
  1894. /*
  1895. * Implementation of Stack that can give minimum in O(1) time all the time
  1896. * This solution uses same data structure for minimum variable, it could be implemented using pointers but that will be more space consuming
  1897. */
  1898.  
  1899. #include <iostream>
  1900. using namespace std;
  1901.  
  1902. typedef struct stackLLNodeType stackLLNode;
  1903.  
  1904. struct stackLLNodeType {
  1905. int item;
  1906. int min;
  1907. stackLLNode *next;
  1908. };
  1909.  
  1910. class DynamicStack {
  1911. private:
  1912. int stackSize;
  1913. stackLLNode *top;
  1914.  
  1915. public:
  1916. DynamicStack();
  1917. ~DynamicStack();
  1918. void push(int x);
  1919. int pop();
  1920. int getMin();
  1921. int size() { return stackSize; }
  1922. };
  1923.  
  1924. void pushOperation(DynamicStack& p_stackObj, int item);
  1925. void popOperation(DynamicStack& p_stackObj);
  1926.  
  1927. int main () {
  1928. DynamicStack stackObj;
  1929.  
  1930. pushOperation(stackObj, 3);
  1931. pushOperation(stackObj, 1);
  1932. pushOperation(stackObj, 2);
  1933. popOperation(stackObj);
  1934. popOperation(stackObj);
  1935. popOperation(stackObj);
  1936. popOperation(stackObj);
  1937. pushOperation(stackObj, 4);
  1938. pushOperation(stackObj, 7);
  1939. pushOperation(stackObj, 6);
  1940. popOperation(stackObj);
  1941. popOperation(stackObj);
  1942. popOperation(stackObj);
  1943. popOperation(stackObj);
  1944.  
  1945. return 0;
  1946. }
  1947.  
  1948. DynamicStack::DynamicStack() {
  1949. // initialization
  1950. stackSize = 0;
  1951. top = NULL;
  1952. }
  1953.  
  1954. DynamicStack::~DynamicStack() {
  1955. stackLLNode* tmp;
  1956. // chain memory deallocation to avoid memory leak
  1957. while (top) {
  1958. tmp = top;
  1959. top = top->next;
  1960. delete tmp;
  1961. }
  1962. }
  1963.  
  1964. void DynamicStack::push(int x) {
  1965. // allocate memory for new node assign to top
  1966. if (top==NULL) {
  1967. top = new stackLLNode;
  1968. top->item = x;
  1969. top->next = NULL;
  1970. top->min = top->item;
  1971. }
  1972. else {
  1973. // allocation of memory
  1974. stackLLNode *tmp = new stackLLNode;
  1975. // assign the new item
  1976. tmp->item = x;
  1977. tmp->next = top;
  1978.  
  1979. // store the minimum so that it does not get lost after pop operation of later minimum
  1980. if (x < top->min)
  1981. tmp->min = x;
  1982. else
  1983. tmp->min = top->min;
  1984.  
  1985. // update top to new node
  1986. top = tmp;
  1987. }
  1988. stackSize++;
  1989. }
  1990.  
  1991. int DynamicStack::pop() {
  1992. // check if stack is empty
  1993. if (top == NULL)
  1994. return -1;
  1995.  
  1996. stackLLNode* tmp = top;
  1997. int curItem = top->item;
  1998. top = top->next;
  1999. delete tmp;
  2000. stackSize--;
  2001. return curItem;
  2002. }
  2003.  
  2004. int DynamicStack::getMin() {
  2005. if (top == NULL)
  2006. return -1;
  2007. return top->min;
  2008. }
  2009. void pushOperation(DynamicStack& p_stackObj, int item) {
  2010. cout<<"Just pushed: "<<item<<endl;
  2011. p_stackObj.push(item);
  2012. cout<<"Current stack min: "<<p_stackObj.getMin()<<endl;
  2013. cout<<"Current stack size: "<<p_stackObj.size()<<endl<<endl;
  2014. }
  2015.  
  2016. void popOperation(DynamicStack& p_stackObj) {
  2017. int popItem = -1;
  2018. if ((popItem = p_stackObj.pop()) == -1 )
  2019. cout<<"Cannot pop. Stack is empty."<<endl;
  2020. else {
  2021. cout<<"Just popped: "<<popItem<<endl;
  2022. if (p_stackObj.getMin() == -1)
  2023. cout<<"No minimum. Stack is empty."<<endl;
  2024. else
  2025. cout<<"Current stack min: "<<p_stackObj.getMin()<<endl;
  2026. cout<<"Current stack size: "<<p_stackObj.size()<<endl<<endl;
  2027. }
  2028. }
  2029.  
  2030. Just pushed: 3
  2031. Current stack min: 3
  2032. Current stack size: 1
  2033.  
  2034. Just pushed: 1
  2035. Current stack min: 1
  2036. Current stack size: 2
  2037.  
  2038. Just pushed: 2
  2039. Current stack min: 1
  2040. Current stack size: 3
  2041.  
  2042. Just popped: 2
  2043. Current stack min: 1
  2044. Current stack size: 2
  2045.  
  2046. Just popped: 1
  2047. Current stack min: 3
  2048. Current stack size: 1
  2049.  
  2050. Just popped: 3
  2051. No minimum. Stack is empty.
  2052. Current stack size: 0
  2053.  
  2054. Cannot pop. Stack is empty.
  2055. Just pushed: 4
  2056. Current stack min: 4
  2057. Current stack size: 1
  2058.  
  2059. Just pushed: 7
  2060. Current stack min: 4
  2061. Current stack size: 2
  2062.  
  2063. Just pushed: 6
  2064. Current stack min: 4
  2065. Current stack size: 3
  2066.  
  2067. Just popped: 6
  2068. Current stack min: 4
  2069. Current stack size: 2
  2070.  
  2071. Just popped: 7
  2072. Current stack min: 4
  2073. Current stack size: 1
  2074.  
  2075. Just popped: 4
  2076. No minimum. Stack is empty.
  2077. Current stack size: 0
  2078.  
  2079. Cannot pop. Stack is empty.
  2080.  
  2081. public interface IMinStack<T extends Comparable<T>> {
  2082. public void push(T val);
  2083. public T pop();
  2084. public T minValue();
  2085. public int size();
  2086. }
  2087.  
  2088. import java.util.Stack;
  2089.  
  2090. public class MinStack<T extends Comparable<T>> implements IMinStack<T> {
  2091. private Stack<T> stack = new Stack<T>();
  2092. private Stack<T> minStack = new Stack<T>();
  2093.  
  2094. @Override
  2095. public void push(T val) {
  2096. stack.push(val);
  2097. if (minStack.isEmpty() || val.compareTo(minStack.peek()) < 0)
  2098. minStack.push(val);
  2099. }
  2100.  
  2101. @Override
  2102. public T pop() {
  2103. T val = stack.pop();
  2104. if ((false == minStack.isEmpty())
  2105. && val.compareTo(minStack.peek()) == 0)
  2106. minStack.pop();
  2107. return val;
  2108. }
  2109.  
  2110. @Override
  2111. public T minValue() {
  2112. return minStack.peek();
  2113. }
  2114.  
  2115. @Override
  2116. public int size() {
  2117. return stack.size();
  2118. }
  2119. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement