Advertisement
Guest User

Untitled

a guest
Nov 15th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. // you can also use imports, for example:
  2. import java.util.*;
  3.  
  4. // you can use System.out.println for debugging purposes, e.g.
  5. // System.out.println("this is a debug message");
  6.  
  7. public class Solution {
  8. private List<Integer> stack=new ArrayList<>();
  9. private ArrayList<Integer> indices = new ArrayList<>();
  10. private boolean transactionStart=false;
  11. public Solution() {
  12. // write your code in Java SE 8
  13.  
  14. }
  15.  
  16. public void push(int value) {
  17. this.stack.add(value);
  18. }
  19.  
  20. public int top() {
  21. if(this.stack.size() > 0 ){
  22. return this.stack.get(this.stack.size()-1);
  23. }
  24. return 0;
  25. }
  26.  
  27. public void pop() {
  28. if(this.stack.size() > 0 ) {
  29. this.stack.remove(this.stack.size()-1);
  30. }
  31. }
  32.  
  33. public void begin() {
  34. this.indices.add(this.stack.size()-1);
  35. this.transactionStart = true;
  36. }
  37.  
  38. public boolean rollback() {
  39. if(this.indices.size() > 0 ){
  40. this.stack = this.stack.subList(0,this.indices.get(this.indices.size()-1)+1);
  41. this.indices.remove(this.indices.size()-1);
  42. return true;
  43. }
  44. return false;
  45. }
  46.  
  47. public boolean commit() {
  48. if(this.indices.size() > 0 ) {
  49. this.indices.remove(this.indices.size()-1);
  50. return true;
  51. }
  52. return false;
  53. }
  54.  
  55. public static void test() {
  56. // Define your tests here
  57. Solution sol = new Solution();
  58. sol.push(42);
  59. sol.push(2);
  60. assert sol.top() == 2 : "top() should be 42";
  61. }
  62. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement