使用Java中的链接列表实现堆栈

时间:2020-02-23 14:34:25  来源:igfitidea点击:

在此程序中,我们将看到如何在Java中使用链接列表实现堆栈。

Stack是一个抽象的数据类型,它演示在第一件出来( LIFO) 行为。
我们将使用链接列表实现相同的行为。

堆叠有两个最重要的操作:

  • Push:我们将把元素推到链接列表的开头,以演示堆栈的推动行为。
  • Pop:我们将删除链接列表的第一个元素以演示堆栈的POP行为。

Java程序:

允许创建一个Java程序来使用链接列表创建堆栈。

package org.igi.theitroad;
 
public class LinkedListStack {
	private Node head; //the first node
 
	//nest class to define linkedlist node
	private class Node {
		int value;
		Node next;
	}
 
	public LinkedListStack() {
		head = null;
	}
 
	//Remove value from the beginning of the list for demonstrating behaviour of stack
	public int pop() throws LinkedListEmptyException {
		if (head == null) {
			throw new LinkedListEmptyException();
		}
		int value = head.value;
		head = head.next;
		return value;
	}
 
	//Add value to the beginning of the list for demonstrating behaviour of stack
	public void push(int value) {
		Node oldHead = head;
		head = new Node();
		head.value = value;
		head.next = oldHead;
	}
 
	public static void main(String args[]) 
	{
		LinkedListStack lls=new LinkedListStack();
		lls.push(20);
		lls.push(50);
		lls.push(80);
		lls.push(40);
		lls.push(60);
		lls.push(75);
		System.out.println("Element removed from LinkedList: "+lls.pop());
		System.out.println("Element removed from LinkedList: "+lls.pop());
		lls.push(10);
		System.out.println("Element removed from LinkedList: "+lls.pop());
		printList(lls.head);
	}
	public static void printList(Node head) {
		Node temp = head;
		while (temp != null) {
			System.out.format("%d ", temp.value);
			temp = temp.next;
		}
		System.out.println();
	}
}
 
/**
 * 
 * Exception to indicate that LinkedList is empty.
 */
 
class LinkedListEmptyException extends RuntimeException {
	private static final long serialVersionUID = 1L;
 
	public LinkedListEmptyException() {
		super();
	}
 
	public LinkedListEmptyException(String message) {
		super(message);
	}
}

运行上面的程序时,我们将得到以下输出:

Element removed from LinkedList: 75
Element removed from LinkedList: 60
Element removed from LinkedList: 10
40 80 50 20