27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 3 | Stacks <strong>and</strong> Queues<br />

33 stack.push(v);<br />

34 }<br />

35 return removed_item;<br />

36 }<br />

37 }<br />

38<br />

39 public class Stack {<br />

40 private int capacity;<br />

41 public Node top, bottom;<br />

42 public int size = 0;<br />

43<br />

44 public Stack(int capacity) { this.capacity = capacity; }<br />

45 public boolean isAtCapacity() { return capacity == size; }<br />

46<br />

47 public void join(Node above, Node below) {<br />

48 if (below != null) below.above = above;<br />

49 if (above != null) above.below = below;<br />

50 }<br />

51<br />

52 public boolean push(int v) {<br />

53 if (size >= capacity) return false;<br />

54 size++;<br />

55 Node n = new Node(v);<br />

56 if (size == 1) bottom = n;<br />

57 join(n, top);<br />

58 top = n;<br />

59 return true;<br />

60 }<br />

61<br />

62 public int pop() {<br />

63 Node t = top;<br />

64 top = top.below;<br />

65 size--;<br />

66 return t.value;<br />

67 }<br />

68<br />

69 public boolean isEmpty() { return size == 0; }<br />

70 public int removeBottom() {<br />

71 Node b = bottom;<br />

72 bottom = bottom.above;<br />

73 if (bottom != null) bottom.below = null;<br />

74 size--;<br />

75 return b.value;<br />

76 }<br />

77 }<br />

1 1 7<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Data Structures

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!