链栈

public class LinkedStack {

	Node head = new Node();
	boolean empty() {
		return head.next == null;
	}
	
	void push(int e) {
		Node n = new Node(e);
		n.next = head.next;
		head.next = n;
	}
	
	int[] pop() {
		int[] arr = new int[2];
		if(empty()) {
			arr[0] = 0;
			return arr;
		}
		arr[0] = 1;
		arr[1] = head.next.data;
		head.next = head.next.next;
		return arr;
	}
	
	int[] top() {
		int[] arr = new int[2];
		if(empty()) {
			arr[0] = 0;
			return arr;
		}
		arr[0] = 1;
		arr[1] = head.next.data;
		
		return arr;
	}
	
	void display() {
		Node p = head.next;
		while(p != null) {
			if(p.next != null)
				System.out.print(p.data + "->");
			else 
				System.out.println(p.data);
			p = p.next;
		}
	}
	
	public static void main(String[] args) {
		LinkedStack ss = new LinkedStack();
		System.out.println(ss.empty());
		ss.push(2);
		ss.push(3);
		ss.display();
		ss.pop();
		ss.display();
		ss.push(1);
		ss.push(2);
		ss.display();
		ss.pop();
		ss.push(4);
		ss.display();
		ss.top();
		ss.display();

	}

}

class Node {
	int data;
	Node next;
	Node() {}
	Node(int e) {
		data = e;
	}
	
}


结果:

true
3->2
2
2->1->2
4->1->2
4->1->2


posted @ 2017-07-26 21:25  cxchanpin  阅读(153)  评论(0)    收藏  举报