Basic operation of single chain table (3): single chain table implementation stack

Keywords: Java

We know that stack is a kind of "last in, first out" data structure. The insertion and deletion of stack are carried out at the head of stack, which is similar to the principle of inserting and deleting elements at the head of single chain table. Therefore, stack can be implemented with one-way chain table.

Java code of single chain table implementation stack:

package parking;

import java.util.Stack;

class Node {

	Object data;
	Node next;

	public Node(Object data) {
		this.data = data;
	}

}

class LinkNode {
	private Node head;
	private int size;

	public LinkNode() {
		this.head = null;
		this.size = 0;
	}

	// Judge whether it is empty
	public boolean isEmpty() {
		return size == 0 ? true : false;
	}

	// Head insertion method
	public void addHNode(Node node) {
		if (head == null) {
			head = node;
		} else {
			node.next = head;
			head = node;
		}
		size++;
	}

	// Output header node, do not delete
	public Object sysHNode() {
		if (head == null) {
			return null;
		}
		Object obj = head.data;
		return obj;
	}

	// Output header node and delete
	public Object sysHnode() {
		if (head == null) {
			return null;
		}
		Object obj = head.data;
		if (head.next == null) {
			head = null;
		} else {
			head = head.next;
		}
		size--;
		return obj;
	}

	public int getSize() {
		// TODO Auto-generated method stub
		return size;
	}

}

public class LinkStack {

	private LinkNode link;

	LinkStack() {
		link = new LinkNode();
	}

	// Judge whether it is empty
	public boolean isEmpty() {
		return link.isEmpty();
	}

	// Push
	private void push(Object obj) {
		Node node = new Node(obj);
		link.addHNode(node);
	}

	// Stack out
	private Object pop() {
		return link.sysHnode();
	}

	// Out of stack, but do not delete the header node
	private Object peek() {
		return link.sysHNode();
	}

	// Get stack size
	private int size() {
		return link.getSize();
	}

	public static void main(String[] args) {
		LinkStack stack = new LinkStack();
		int i;
		for (i = 0; i < 5; i++) {
			stack.push(i);
		}
		System.out.println("Stack size:" + stack.size());
		System.out.println("Top element of stack:" + stack.peek());
		while (!stack.isEmpty()) {
			System.out.print(stack.pop() + "-->");
		}

	}
}

Effect:

Stack size: 5
 Stack top element: 4
4-->3-->2-->1-->0-->

 

My motto: No, I can learn; backward, I can catch up; falling, I can stand up; I can do it.   

Posted by Hades on Tue, 28 Jan 2020 08:06:39 -0800