Sie sind auf Seite 1von 18

DATA STRUCTURES AND

ALGORITHMS

Implement 2 Stacks in an Array


1. public class twostacks {
2.
3. static class TwoStacks {
4. int size;
5. int top1, top2;
6. int arr[];
7.
8. TwoStacks(int n) {
9. arr = new int[n];
10. size = n;
11. top1 = -1;
12. top2 = size;
13. }
14.
15. void push1(int x) {
16. if (top1 < top2 - 1) {
17. top1++;
18. arr[top1] = x;
19. } else {
20. System.out.println("Stack Overflow");
21. System.exit(1);
22. }
23. }
24.
25. void push2(int x) {
26. if (top1 < top2 - 1) {
27. top2--;
28. arr[top2] = x;
29. } else {
30. System.out.println("Stack Overflow");
31. System.exit(1);
32. }
33. }
34.
35. int pop1() {
36. if (top1 >= 0) {
37. int x = arr[top1];
38. top1--;
39. return x;
40. } else {
41. System.out.println("Stack Underflow");
42. System.exit(1);
43. }
44. return 0;
45. }
46.
47. int pop2() {
48. if (top2 < size) {
49. int x = arr[top2];
50. top2++;
51. return x;
52. } else {
53. System.out.println("Stack Underflow");
54. System.exit(1);
55.
56. }
57. return 0;
58. }
59.
60. }
61.
62. public static void main(String args[]) {
63. TwoStacks ts = new TwoStacks(5);
64. ts.push1(25);
65. ts.push2(14);
66. ts.push2(75);
67. ts.push1(22);
68. ts.push2(13);
69. System.out.println("popped element :" + " stack 1 : " + ts.pop1());
70. ts.push2(9);
71. System.out.println("popped element :" + " stack 2 : " + ts.pop2());
72. ts.push1(22);
73. ts.push2(13);
74. }
75. }
OUTPUT:

Implementing a queue using 2 stacks


1. import java.util.Stack;
2.
3. public class QUS {
4.
5. private static class QueueUsingStack {
6. Stack<Integer> s1;
7. Stack<Integer> s2;
8.
9. public QueueUsingStack() {
10. s1 = new Stack<>();
11. s2 = new Stack<>();
12. }
13.
14. public void addq(int val) {
15. s1.push(val);
16. }
17.
18. public int deq() {
19. while (s1.size() != 1)
20. s2.push(s1.pop());
21.
22. int rv = s1.pop();
23.
24. while (s2.size() != 0)
25. s1.push(s2.pop());
26.
27. return rv;
28. }
29.
30. public int front() {
31. while (s1.size() != 1)
32. s2.push(s1.pop());
33.
34. int rv = s1.peek();
35.
36. while (s2.size() != 0)
37. s1.push(s2.pop());
38. return rv;
39. }
40.
41. }
42.
43. public static void main(String[] args) {
44.
45. QueueUsingStack q1 = new QueueUsingStack();
46. q1.addq(10);
47. q1.addq(3);
48. q1.addq(105);
49. q1.addq(32);
50. System.out.println(q1.deq());
51. q1.addq(103);
52. q1.addq(31);
53. System.out.println(q1.deq());
54. System.out.println(q1.deq());
55. System.out.println(q1.deq());
56.
57. }
58.
59. }

OUTPUT:

Implement Sorted LinkedList


1. public class SortedLL {
2.
3. static class LinkedList {
4. Node head;
5. int size;
6.
7. static class Node {
8. int data;
9. Node next;
10.
11. Node(int data) {
12. this.data = data;
13. }
14. }
15.
16. public LinkedList() {
17. this.size = 0;
18. this.head = null;
19. }
20.
21. void sortedInsert(int data) {
22. Node nd = new Node(data);
23.
24. if (size == 0) {
25. head = nd;
26. size = 1;
27. return;
28. }
29.
30. size++;
31. if (data < head.data) {
32. nd.next = head;
33. head = nd;
34. return;
35. } else {
36. Node p;
37. for (p = head; p.next != null && p.next.data < data; p = p.next) {
38. // blank
39. }
40. nd.next = p.next;
41. p.next = nd;
42.
43. }
44.
45. }
46.
47. void printList() {
48. Node temp = head;
49. while (temp != null) {
50. System.out.print(temp.data + " ");
51. temp = temp.next;
52. }
53. }
54.
55. boolean isEmpty() {
56. if (size == 0) {
57. return true;
58. }
59.
60. return false;
61. }
62.
63. }
64.
65. public static void main(String args[]) {
66. LinkedList llist = new LinkedList();
67. llist.sortedInsert(10);
68. llist.sortedInsert(102);
69. llist.sortedInsert(106);
70. llist.sortedInsert(103);
71. llist.sortedInsert(110);
72. llist.sortedInsert(9);
73. llist.printList();
74.
75. }
76. }

OUTPUT:

Implement Priority Queue using LinkedList


1.
2. public class PriorityQueue {
3.
4. static class pq {
5. class Node {
6. int data;
7. int priority;
8. Node next;
9.
10. public Node(int data, int priority) {
11. this.data = data;
12. this.priority = priority;
13. }
14.
15. }
16.
17. Node head;
18.
19. int peek() {
20. return head.data;
21. }
22.
23. int pop() {
24. Node temp = head;
25. head = head.next;
26. return temp.data;
27. }
28.
29. void push(int d, int p) {
30.
31. Node temp = new Node(d, p);
32.
33. if (head == null) {
34. head = temp;
35. return;
36. }
37.
38. if (head.priority > p) {
39. temp.next = head;
40. head = temp;
41. return;
42. }
43.
44. Node start = head;
45. while (start.next != null && start.next.priority < p) {
46. start = start.next;
47. }
48.
49. temp.next = start.next;
50. start.next = temp;
51.
52. }
53.
54. int isEmpty() {
55. return (head == null) ? 1 : 0;
56. }
57. }
58.
59. public static void main(String args[]) {
60.
61. pq pq = new pq();
62. pq.push(4, 1);
63. pq.push(5, 2);
64. pq.push(6, 3);
65. pq.push(7, 0);
66.
67. while (pq.isEmpty() == 0) {
68. System.out.println(pq.peek());
69. pq.pop();
70. }
71.
72. }
73. }
OUTPUT:

Implement Quick Sort in a Doubly LinkedList


1. public class QuickSort {
2.
3. static class doublyLL {
4. Node head;
5.
6. class Node {
7. private int data;
8. private Node next;
9. private Node prev;
10.
11. Node(int d) {
12. data = d;
13. next = null;
14. prev = null;
15. }
16. }
17.
18. Node tail(Node node) {
19. while (node.next != null)
20. node = node.next;
21. return node;
22. }
23.
24. Node partition(Node l, Node h) {
25.
26. int x = h.data;
27.
28. Node i = l.prev;
29.
30. for (Node j = l; j != h; j = j.next) {
31. if (j.data <= x) {
32. // Similar to i++ for array
33. i = (i == null) ? l : i.next;
34. int temp = i.data;
35. i.data = j.data;
36. j.data = temp;
37. }
38. }
39. i = (i == null) ? l : i.next; // Similar to i++
40. int temp = i.data;
41. i.data = h.data;
42. h.data = temp;
43. return i;
44. }
45.
46. void quickSortR(Node l, Node h) {
47. if (h != null && l != h && l != h.next) {
48. Node temp = partition(l, h);
49. quickSortR(l, temp.prev);
50. quickSortR(temp.next, h);
51. }
52. }
53.
54. public void quickSort(Node node) {
55.
56. Node head = tail(node);
57.
58. quickSortR(node, head);
59. }
60.
61. public void display(Node head) {
62. while (head != null) {
63. System.out.print(head.data + " ");
64. head = head.next;
65. }
66. }
67.
68. void push(int new_Data) {
69. Node new_Node = new Node(new_Data); /* allocate node */
70.
71. if (head == null) {
72. head = new_Node;
73. return;
74. }
75.
76. new_Node.next = head;
77.
78. head.prev = new_Node;
79.
80. new_Node.prev = null;
81.
82. head = new_Node;
83. }
84.
85. }
86.
87. public static void main(String[] args) {
88. doublyLL list = new doublyLL();
89.
90. list.push(5);
91. list.push(20);
92. list.push(4);
93. list.push(3);
94. list.push(30);
95.
96. System.out.println("Linked List before quick sorting ");
97. list.display(list.head);
98. System.out.println("\nLinked List after quick sorting");
99. list.quickSort(list.head);
100. list.display(list.head);
101.
102. }
103. }

OUTPUT:
Evaluate Infix Expression using stacks
1. import java.util.Scanner;
2. import java.util.Stack;
3.
4. public class evaluateInfix {
5.
6. public static void main(String[] args) {
7.
8. Scanner scn = new Scanner(System.in);
9.
10. String input = scn.next();
11.
12. System.out.println(evaluateInfixExpr(input));
13. }
14.
15. public static String infixtopostfix(String str) {
16.
17. // Containing the expression
18. str = '(' + str + ')';
19.
20. Stack<String> st = new Stack<>();
21. StringBuilder sb = new StringBuilder("");
22.
23. for (int i = 0; i < str.length();) {
24. char c = str.charAt(i);
25.
26. if (Character.isDigit(c)) {
27. StringBuilder num = new StringBuilder("");
28. while (i < str.length() && Character.isDigit(str.charAt(i))) {
29. num.append(str.charAt(i));
30. i++;
31. }
32. sb.append(num + ",");
33. } else if (c == '(') {
34. st.push("" + c);
35. i++;
36. } else if (c == ')') {
37. while (st.size() != 0) {
38. if (st.peek().compareTo("(") == 0) {
39. st.pop();
40. break;
41. }
42. sb.append(st.pop() + ",");
43. }
44. i++;
45. } else {
46. // If an operator is the first thing in your expression, or
47. // another operator comes after it, or comes after a left
48. // parenthesis, then it's an unary operator.
49. char op;
50.
51. if (i == 0 || str.charAt(i - 1) == '(' || isOperator(str.charAt(i -
1) + "") != 0) {
52. op = '.';
53. } else {
54. op = str.charAt(i);
55. }
56.
57. if (op == '^') {
58. while (st.isEmpty() == false && getPriority(st.peek().charAt(0)
) > getPriority(op)) {
59. sb.append(st.pop() + ",");
60. }
61. st.push(op + "");
62. } else {
63. while (st.isEmpty() == false && getPriority(st.peek().charAt(0)
) >= getPriority(op)) {
64. sb.append(st.pop() + ",");
65. }
66. st.push(op + "");
67. }
68.
69. i++;
70.
71. }
72.
73. }
74.
75. return sb.toString();
76. }
77.
78. public static int evaluateInfixExpr(String str) {
79. String postfixExpression = infixtopostfix(str);
80.
81. String[] expr = postfixExpression.split(",");
82.
83. Stack<Integer> st = new Stack<>();
84.
85. for (int i = 0; i < expr.length; i++) {
86. String curr = expr[i];
87. if (isOperator(expr[i]) == 0) {
88. st.add(Integer.parseInt(expr[i]));
89. } else {
90. if (expr[i].charAt(0) == '.') {
91. st.push(-1 * st.pop());
92. } else {
93. int b = st.pop();
94. int a = st.pop();
95. st.push(operate(a, b, expr[i].charAt(0)));
96. }
97.
98. }
99. }
100. return st.peek();
101. }
102.
103. public static int operate(int a, int b, char op) {
104. switch (op) {
105. case '+': {
106. return a + b;
107. }
108. case '-': {
109. return a - b;
110. }
111. case '*': {
112. return a * b;
113. }
114. case '/': {
115. return a / b;
116. }
117. case '^': {
118. return (int) Math.pow(a, b);
119. }
120. case '%': {
121. return a % b;
122. }
123. }
124. return 0;
125. }
126.
127. public static int getPriority(char c) {
128.
129. switch (c) {
130. case '(':
131. return 0;
132. case '+':
133. case '-':
134. return 1;
135. case '*':
136. case '%':
137. case '/':
138. return 2;
139. case '^':
140. return 3;
141. case '.':
142. return 4;
143. }
144.
145. return 0;
146. }
147.
148. public static int isOperator(String s) { // return 0 if not operator and
2
149. // for operators
150.
151. if (s.compareTo("+") == 0 || s.compareTo("-
") == 0 || s.compareTo("*") == 0 || s.compareTo("/") == 0
152. || s.compareTo("%") == 0 || s.compareTo("^") == 0 || s.compa
reTo(".") == 0) {
153. return 2;
154. }
155.
156. return 0;
157. }
158.
159. }

OUTPUT:

Implement BST and Display it


1. import java.util.Arrays;
2.
3. public class bst {
4.
5. public static class BST {
6. private class node {
7. int data;
8. node left;
9. node right;
10.
11. public node(int data) {
12. this.data = data;
13. }
14.
15. }
16.
17. node root;
18.
19. public BST(int[] sorted) {
20. root = construct(sorted, 0, sorted.length - 1);
21. }
22.
23. private node construct(int[] sa, int lo, int hi) {
24. if (lo > hi)
25. return null;
26.
27. node node = new node(sa[(lo + hi) / 2]);
28.
29. node.left = construct(sa, lo, (lo + hi) / 2 - 1);
30. node.right = construct(sa, (lo + hi) / 2 + 1, hi);
31.
32. return node;
33.
34. }
35.
36. public void display() {
37. display(root);
38. }
39.
40. private void display(node node) {
41.
42. if (node == null)
43. return;
44.
45. String s = node.left == null ? "-1 " : node.left.data + " ";
46. s += "-> " + node.data;
47. s += node.right == null ? " <- -1" : " <- " + node.right.data;
48.
49. System.out.println(s);
50.
51. display(node.left);
52. display(node.right);
53. }
54.
55. public boolean find(int data) {
56. return find(root, data);
57. }
58.
59. private boolean find(node node, int data) {
60. if (node == null)
61. return false;
62. if (node.data == data)
63. return true;
64. boolean b = false;
65. if (data < node.data)
66. b = find(node.left, data);
67.
68. else
69. b = find(node.right, data);
70.
71. return b;
72. }
73.
74. public int max() {
75. return max(root);
76.
77. }
78.
79. private int max(node node) {
80. if (node.right == null) {
81. return node.data;
82. }
83.
84. int maxval = max(node.right);
85. return maxval;
86. }
87.
88. public int min() {
89. return min(root);
90.
91. }
92.
93. private int min(node node) {
94. if (node.left == null) {
95. return node.data;
96. }
97.
98. int minval = min(node.left);
99. return minval;
100. }
101.
102. public void addnode(int data) {
103. addnode(root, data);
104. }
105.
106. private void addnode(node node, int data) {
107.
108. if (data < node.data) {
109. if (node.left == null) {
110. node child = new node(data);
111. node.left = child;
112. } else
113. addnode(node.left, data);
114. } else {
115. if (node.right == null) {
116. node child = new node(data);
117. node.right = child;
118. } else
119. addnode(node.right, data);
120. }
121. }
122. }
123.
124. public static void main(String[] args) {
125. int[] arr = { 12, 55, 2, 4, 76, 45, 68, 9, 14 };
126. Arrays.sort(arr);
127.
128. BST b1 = new BST(arr);
129.
130. b1.display();
131.
132. b1.addnode(36);
133. b1.display();
134.
135. System.out.println(b1.find(45));
136. System.out.println("max=" + b1.max());
137. System.out.println("min=" + b1.min());
138.
139. }
140. }
OUTPUT:

Implement AVL Tree


1.
2. import java.util.Arrays;
3.
4. public class avl {
5.
6. public static class AVL {
7. private class node {
8. int data;
9. node left;
10. node right;
11. int ht;
12. int balf;
13.
14. public node(int data) {
15. this.data = data;
16. }
17.
18. }
19.
20. node root;
21.
22. public AVL(int[] sorted) {
23. root = construct(sorted, 0, sorted.length - 1);
24. }
25.
26. private node construct(int[] sa, int lo, int hi) {
27. if (lo > hi)
28. return null;
29.
30. node node = new node(sa[(lo + hi) / 2]);
31.
32. node.left = construct(sa, lo, (lo + hi) / 2 - 1);
33. node.right = construct(sa, (lo + hi) / 2 + 1, hi);
34.
35. node.ht = getht(node);
36. node.balf = get_balf(node);
37. return node;
38.
39. }
40.
41. private int getht(node node) {
42. int lht = -1;
43. int rht = -1;
44.
45. if (node.left != null)
46. lht = node.left.ht;
47.
48. if (node.right != null)
49. rht = node.right.ht;
50.
51. return Math.max(lht, rht) + 1;
52. }
53.
54. private int get_balf(node node) { // balf : balance factor
55. int lht = -1;
56. int rht = -1;
57.
58. if (node.left != null)
59. lht = node.left.ht;
60.
61. if (node.right != null)
62. rht = node.right.ht;
63.
64. return lht - rht;
65. }
66.
67. public int max() {
68. return max(root);
69.
70. }
71.
72. private int max(node node) {
73. if (node.right == null) {
74. return node.data;
75. }
76.
77. int maxval = max(node.right);
78. return maxval;
79. }
80.
81. public void display() {
82. System.out.println("----------------------------");
83. display(root);
84. System.out.println("----------------------------");
85. }
86.
87. private void display(node node) {
88.
89. if (node == null)
90. return;
91.
92. String s = node.left == null ? "-1 " : node.left.data + " ";
93. s += "-> " + node.data + "[" + node.ht + "," + node.balf + "] ";
94. s += node.right == null ? " <- -1" : " <- " + node.right.data;
95.
96. System.out.println(s);
97.
98. display(node.left);
99. display(node.right);
100. }
101.
102. public void addnode_return(int data) {
103. root = addnode_return(root, data);
104. }
105.
106. private node addnode_return(node node, int data) {
107. if (node == null) {
108.
109. node child = new node(data);
110. child.ht = 0;
111. child.balf = 0;
112. return child;
113. }
114.
115. if (data < node.data) {
116. node.left = addnode_return(node.left, data);
117. } else if (data > node.data) {
118. node.right = addnode_return(node.right, data);
119. }
120.
121. node.ht = getht(node);
122. node.balf = get_balf(node);
123. if (Math.abs(node.balf) > 1) {
124. node = rotate(node);
125. }
126.
127. return node;
128. }
129.
130. private node rotate(node node) {
131. if (node.balf > 0) {
132. if (get_balf(node.left) > 0) { // LL
133. node y = node.left;
134. node.left = y.right;
135. y.right = node;
136.
137. node.ht = getht(node);
138. node.balf = get_balf(node);
139. y.ht = getht(y);
140. y.balf = get_balf(y);
141.
142. return y;
143. }
144.
145. else if (get_balf(node.left) < 0) {// LR
146. node y = node.left;
147. node x = y.right;
148. y.right = x.left;
149. x.left = y;
150.
151. node.left = x.right;
152. x.right = node;
153.
154. node.ht = getht(node);
155. node.balf = get_balf(node);
156. y.ht = getht(y);
157. y.balf = get_balf(y);
158. x.ht = getht(x);
159. x.balf = get_balf(x);
160.
161. return x;
162. }
163. } else if (node.balf < 0) {
164. if (get_balf(node.right) > 0) {// RL
165. node y = node.right;
166. node x = y.left;
167. y.left = x.right;
168. x.right = y;
169.
170. node.right = x.left;
171. x.left = node;
172.
173. node.ht = getht(node);
174. node.balf = get_balf(node);
175. y.ht = getht(y);
176. y.balf = get_balf(y);
177. x.ht = getht(x);
178. x.balf = get_balf(x);
179.
180. return x;
181. }
182.
183. else if (get_balf(node.right) < 0) {// RR
184. node y = node.right;
185. node.right = y.left;
186. y.left = node;
187. node.ht = getht(node);
188. node.balf = get_balf(node);
189. y.ht = getht(y);
190. y.balf = get_balf(y);
191. return y;
192. }
193. }
194.
195. return null;
196.
197. }
198.
199. }
200.
201. public static void main(String[] args) {
202. int[] arr = { 12, 55, 2, 4, 76, 45, 68, 9, 14 };
203. Arrays.sort(arr);
204.
205. AVL b1 = new AVL(arr);
206.
207. System.out.println("------------------");
208. System.out.println("left child -
> node value [bal. factor,height] <- right child");
209. System.out.println("------------------\n");
210.
211. b1.display();
212.
213. b1.addnode_return(36);
214. b1.display();
215.
216. System.out.println("max=" + b1.max());
217.
218. }
219. }
OUTPUT:

Das könnte Ihnen auch gefallen