赞
踩
链表也可以实现栈,通过在表头插入元素的方式实现push操作,删除链表的表头结点的方式实现pop操作
/** * 单向链表 */ public class ListNode { private int data; private ListNode next; public ListNode(int data) { this.data = data; } public void setData(int data) { this.data = data; } public int getData() { return this.data; } public void setNext(ListNode next) { this.next = next; } public ListNode getNext() { return this.next; } }
/** * 基于链表的栈的实现 */ public class LinkedListStack { private ListNode head = null; public LinkedListStack() { head = new ListNode(0); } public void Push(int data) { if (head == null) { head = new ListNode(data); } else if (head.getData() == 0) { head.setData(data); } else { ListNode node = new ListNode(data); node.setNext(head); head = node; } } public int pop() { if (head == null) { throw new EmptyStackException(); } else { int data = head.getData(); head = head.getNext(); return data; } } public int top() { if (head == null) { return 0; } else { return head.getData(); } } public boolean isEmpty() { return head == null; } public void deleteStack() { head = null; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。