Assignment Title Simple Data Structures Computer Science 12
Assignment Title :- Simple Data Structures (Computer Science 120)
Use a linked list to implement a stack. The stack should store characters. The stack should support the following operations/functions:-
1. Push:- Which adds a new element to the top of the stack. Push should take a character as an argument (the character to be pushed onto the stack).
2. Pop:- Which removes an element from the top of the stack. Pop should return a character - the character popped o the stack. If the stack is empty when pop is called it should return the null character.
3. Empty:- Which returns a true or false value depending on whether the stack is empty of not.
To test the stack class push the following characters onto the stack t, e, s, t, a, n, g. Pop three characters o the stack. Then push the characters i, n, g onto the stack. Finally pop all of the remaining characters o the stack and print them in the order they are popped. You should use a loop, using the empty operation as part of the stopping condition, to pop and print the stack.
Solution
//coding in java as language is not mentioned
public class Stack {
class Node {
char value;
Node next;
public char getValue() {
return value;
}
public void setValue(char value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Node s = null; // start node
public void Push(char n){
Node n1 = new Node();
n1.setValue(n);
n1.setNext(null);
if(s == null) s = n1;
else {
n1.setNext(s);
s = n1;
}
}
public char Pop() {
if(s == null){
return \' \'; //error if stack is empty
}
else
{
char n = s.getValue();
s = s.getNext();
return n;
}
}
public boolean empty() {
if(s == null) return true;
return false;
}
}
//-------------------------------------------------------------------
public class Tester {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack s = new Stack();
s.Push(\'t\');
s.Push(\'e\');
s.Push(\'s\');
s.Push(\'t\');
s.Push(\'a\');
s.Push(\'n\');
s.Push(\'g\');
System.out.println(s.Pop());
System.out.println(s.Pop());
System.out.println(s.Pop());
s.Push(\'i\');
s.Push(\'n\');
s.Push(\'g\');
while(!s.empty())
System.out.println(s.Pop());
}
}
//----------------------------------------------------------------
Output:
g
n
a
g
n
i
t
s
e
t

