/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gcode.chapter3;
/**
*
*
*/
public class LinkList {
public Node head,tail; /* Point to head and tail of list */
/* Constructor */
public LinkList(){
head = null;
tail = null;
}
/* isEmpty */
public boolean isEmpty(){
return head==null;
}
/* To insert at the beginning of the link list (push) */
public void insertAtHead(int d){
Node newNode = new Node(d); /* Create a new node */
/* First entry */
if(isEmpty()){
tail = newNode; /* We want to make the tail look at this node */
newNode.next = null;
}
newNode.next = head;
head = newNode;
}
/* To insert at the end of the list (enqueue) */
public void insertAtTail(int d){
Node newNode = new Node(d);
/* First entry */
if(isEmpty()){
head = newNode;
tail = newNode;
newNode.next = null;
}
tail.next = newNode; /* Add in new node to end */
tail = tail.next; /* Move tail to the end */
}
/* To delete the first of the link list (pop, dequeue) */
public int removeAtHead(){
Node tmp = head;
head = head.next; /* Move head over */
tmp.next = null;
return tmp.data;
}
public void displayList(){
Node tracker;
System.out.println("displaying list");
for(tracker = head; tracker != null; tracker=tracker.next){
tracker.displayNode();
}
System.out.println("---");
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gcode.chapter3;
/**
*/
public class MyStack {
public Node top, minptr;
public int min;
public LinkList l;
/* Constructor */
public MyStack(){
l = new LinkList();
top = l.head;
minptr = top;
min = 999999; /* large value */
}
/* push */
public void push(int d){
l.insertAtHead(d);
if(d < min){
min = d; /* Replace min */
minptr = top; /* Make it point to the top of stack */
}
}
/* pop */
public int pop(){
return l.removeAtHead();
}
/* peek at top */
public int top(){
return top.data;
}
public boolean isEmpty(){
return l.isEmpty();
}
public void displayStack(){
System.out.println("Displaying stack...");
l.displayList();
}
public int getMinimum(){
return minptr.data;
}
/* Main function */
public static void main(String[] args) {
MyStack s = new MyStack();
s.push(10);
s.push(20);
s.push(30);
s.displayStack();
s.pop();
s.displayStack();
return;
}
}
/* OUTPUT */
Displaying stack...
displaying list
---
Displaying stack...
displaying list
---
30 20 10 20 10 BUILD SUCCESSFUL (total time: 1 second)