1. Defining the Stack interface
Package stack;
Public interface Istack {
public void clear ();
public boolean isEmpty ();
public int length ();
Public Object Peek ();
public void push (Object x) throws Exception;
Public Object pop ();
}
2. Defining node Nodes
Package stack;
Import Class2. Node;
public class Node {
Private Object data;
Private Node Next;
No parameter constructor
Public Node () {
This (null,null);
This.data=null;
This.next=null;
}
constructor with one parameter
Public Node (Object data) {
This (data,null); Effect on the same
This.data=data;
This.next=null;
}
A constructor with two parameters
Public Node (Object Data,node next) {
This.data=data;
This.next=next;
}
Gets the data for the current node.
Public Object GetData () {
return data;
}
Gets the pointer field of the current node.
Public Node GetNext () {
return next;
}
Assign a value to the current node
public void SetData (Object data) {
This.data=data;
}
Modify the pointer field of the current node
public void Setnext (Node next) {
This.next=next;
}
}
3. Implement the interface of the stack and define the link stacks and methods
Package stack;
public class Linkstack implements istack{
Private Node top;//Just declare it
Empty the link stack
public void Clear () {
Top=null;
}
Determine if the link stack is empty
public Boolean isEmpty () {
if (top==null)
return true;
Else
return false;
}
Calculate the length of the chain stack, the time complexity is O (n)
public int Length () {
int i=0;
while (top!=null) {//differs from the sequence stack, top points to the stack top element of the chain stack
i++; The stack top points to the next top=0 of the top element of the stack, pointing to the top of the stack as 1
Top=top.getnext ();
}
return i;
}
Returns the stack top element of the chain stack
Public Object Peek () {
if (top!=null) {
return Top.getdata ();
}
else{
return null;
}
}
To do the stack operation of the chain
public void push (Object x) throws exception{//first joins the new node and then moves the top
Node p=new node (x);//Construct a new node first
P.setnext (top);//Set the index of the next node for the node.
p=top;//Mobile Top
}
Do the stack operation of the chain stack
Public Object pop () {
if (top!=null) {
Node p=top;//first remove the node, then move the top.
Top=top.getnext ();
return P.getdata ();
}
else{
return null;
}
}
}
Definition of a data structure (Java language description) chain stack