Sunday, February 6, 2022

Linkedlist to stack adapter

I/O:

push 10 push 20 push 5 push 8 push 2 push 4 push 11 top size pop top size pop top size pop top size pop top size pop top size pop top size pop quit


O/P:

11 7 11 4 6 4 2 5 2 8 4 8 5 3 5 20 2 20 10 1 10



import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;

public class LinkedList_To_Stack_Adapter {

public static class LLToStackAdapter {
LinkedList<Integer> list;

public LLToStackAdapter() {
list = new LinkedList<>();
}

// write your code here
int size() {
return list.size();
}

// write your code here
void push(int val) {
list.addFirst(val);
}

// write your code here
int pop() {
return list.removeFirst();
}

// write your code here
int top() {
return list.get(0);
}
}

public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
LLToStackAdapter st = new LLToStackAdapter();

String str = br.readLine();
while (str.equals("quit") == false) {
if (str.startsWith("push")) {
int val = Integer.parseInt(str.split(" ")[1]);
st.push(val);
} else if (str.startsWith("pop")) {
int val = st.pop();
if (val != -1) {
System.out.println(val);
}
} else if (str.startsWith("top")) {
int val = st.top();
if (val != -1) {
System.out.println(val);
}
} else if (str.startsWith("size")) {
System.out.println(st.size());
}
str = br.readLine();
}
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...