public class StackBaseOnLinkedList {
private Node head;
//入栈
public void push(Node node) {
if(head==null)
head = node;
else
//头插法
node.next = head;
head = node;
}
//出栈,返回-1表示链表为空
public int pop() {
if(head==null)
return -1;
else
{
int temp;
temp=head.getData();
head=head.next;
}
return 0;
}
public void printAll() {
if(head==null)
return ;
Node node = head;
while(node!=null)
{
System.out.print(node.getData()+" ");
node = node.next;
}
}
public static void main(String[] args) {
StackBaseOnLinkedList stackBaseOnLinkedList = new StackBaseOnLinkedList();
stackBaseOnLinkedList.push(new Node(null, 1));
stackBaseOnLinkedList.push(new Node(null, 4));
stackBaseOnLinkedList.push(new Node(null, 7));
stackBaseOnLinkedList.pop();
stackBaseOnLinkedList.push(new Node(null, 7));
stackBaseOnLinkedList.printAll();
}
}
class Node{
Node next;
int data;
public int getData() {
return data;
}
public Node(Node next, int data) {
this.next = next;
this.data = data;
}