Stack in Java--栈

In this session, we discuss stack data structure and then learn how to implement it using an array and linked list.

本章节我们学习栈这个数据结构并用数组和链表来实现栈。

Stack

In everyday life, a stack is a familiar thing.

You might see a stack of books on your desk, a stack of dishes in the cafeteria, a stack of towels in the linen closet, or a stack of boxes in the attic.

When you add an item to a stack, you place it on top of the stack.

When you remove an item, you take the topmost one.

This topmost item is the last one that was added to the stack. So when you remove an item, you remove the item added most recently. That is, the last item added to the stack is the first one removed.
In the computer science world last-in, first-out is exactly the behaviour required by many important algorithms. These algorithms often use the abstract data type stack, which is an ADT that exhibits a last-in, first-out behaviour. For example, a compiler uses a stack to interpret the meaning of an algebraic expression, and a run-time environment uses a stack when executing a recursive method.
Slide 4:Stacks are a fundamental data structure. They are used in many applications, including the following.
Internet Web browsers store the addresses of recently visited sites on a stack. Each time a user visits a new site, that site’s address is “pushed” onto the stack of addresses. The browser then allows the user to “pop” back to previously visited sites using the “back” button.
Text editors usually provide an “undo” mechanism that cancels recent editing operations and reverts to former states of a document. This undo operation can be accomplished by keeping text changes in a stack.
Slide 5:
The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack. When a method is called, the JVM pushes on the stack a frame containing Local variables and return value. Program counter, keeping track of the statement being executed. When a method ends, its frame is popped from the stack and control is passed to the method on top of the stack. This implementation allows for recursion.
Slide 6:
 
A stack can be viewed as an abstract data type that supports three main operations, traditionally called push, peek, and pop. The push operation takes a single item and adds it to the top of the stack. The peek operation returns the item currently at the top of the stack, but does not remove it. The pop operation removes (and returns) the item currently stored at the top of the stack. The following specifications define a set of operations for the ADT stack.
Slide 7:
The Java Collection Framework provides a Stack class that supports generic types. The class is in the java.util package
Slide 8:
The JCF stack can be used to create stacks of String, numeric values, or any other types. Next Slide demonstrates the use of the JCF Stack class to work with strings
Slide 9:
This slide shows a simple demonstration of the use of the Stack class. The program creates a stack and pushes String objects onto it. Then it keeps popping the stack and printing the values popped until the stack is empty. Notice that the last-in-first-out nature of the stack causes the strings to be popped in the reverse of the order in which they were pushed.
Slide 10:
The JCF Stack class does not support stacks of primitive types. To create a stack that can store a primitive type, create a stack of the corresponding wrapper type.
Slide 11:
For example, to have a stack of int, you must create a stack of Integer as shown in this slide.
Slide 12:
Once a stack of a wrapper type has been declared and instantiated, you can use the primitive type in all stack methods.
The compiler automatically boxes primitive values passed as parameters to the stack methods to form the required wrapper class types.
Slide 13:
The compiler automatically unboxes wrapper types returned as values by the stack methods to form the corresponding primitive value
Slide 14:
The use of stacks of primitive types is illustrated in the codes shown in this slide. The program pushes some numbers onto a stack, then pops and prints them.
Slide 15:
This slide show the implementation of Stack ADT in Java.
Slide 16:
If we want a method to return a value that signals a problem, such as an empty collection, the value must have the return type of the method. Since there is no entry to remove from the collection, it is natural to return null. Also we can throw an exception to signal a problem.
 

Slide 17:
Stack is just a list that enforces last-in-first-out access. The idea is simple. You create an array large enough to hold the largest number of items you will need to have in the stack at any given time, say, four (the capacity of a stack in a real application would likely be much larger), and you use an integer index, top, to point to the next slot in the array that is available to receive an item. Push can be implemented so it stores items at the end of the array. Pop can be implemented so it returns the item at the end of the array.
Slide 18:
This slide shows how the top index is incremented when an element is pushed to the stack.
Slide 19:
Thus, for a stack of integers, you would have an array that holds stack elements and a pointer to the top of the stack as shown in this slide.
The constructor defines the capacity of the stack and places the top pointer to the first of the stack.
Slide 20:
This slide shows the method for adding an item to the stack. To push a new item x, first we check to see if there is room in the stack. If so, we place it in the slot pointed to by top and then increment top to point to the next slot. If the stack has no room, we throw an exception.
Slide 21:
This slide shows the method to retrieve an item from the stack. The pop method checks to see if the stack is empty before attempting to access the item at the top of the stack, and throw EmptyStackException if the stack is empty.
The pop method needs to return the value and to decrement the stack pointer to indicate that the stack slot currently holding the item at the top of the stack is becoming available.
Slide 22:
The exception thrown when an attempt is made to push a value onto a stack whose array if full is called a stack overflow exception.
•    throw new StackOverFlowError();
The exception thrown when an attempt is made to pop an empty stack is sometimes called stack underflow.
•    throw new EmptyStackException();
Slide 23:
This slide shows the empty method. The boolean expression top == 0 is true when the stack is empty and false when it is not, so the empty method simply returns the value of that expression:
return top == 0;
 

Slide 24:
This slide shows the peek method which returns the item currently at the “top” of the stack. It checks to see if the stack is empty before attempting to access the item at the top of the stack, and throw EmptyStackException if the stack is empty.
Slide 25:
The stack implemented in the previous slides is a stack of integers. Writing a stack that works with other types is similar. For example, to write a stack that works with String objects, we would modify the ArrayStack class by changing all occurrences of int that refer to the type of the items being stored in the stack to String.
One main change must be made to the pop method when the stack is being used to store object types: the array entry referring to the stack item being removed must be set to null to facilitate garbage collection of the item being removed from the stack as shown in this slide.
Slide 26:
This slide shows how the pop method is modified to work with string objects .

栈的链表实现

A stack can be implemented by using any type of list object, including the LinkedList class in the java.util package, to hold the stack items. The LinkedList class, however, supports many operations that are not needed when all we need is a stack: for example, most applications of stacks do not need iterators, or the ability to add and remove items from the middle of the list. We can avoid this additional overhead by basing a stack on a simple linked list that we code ourselves.
Slide 28:
Inside the LinkedStack class, we will have a reference to a linked list of items. A reference top will point to the node at the front of the list: this node will be the one removed by the next call to pop.
Slide 29:
The linked list will be based on the following Node class, declared private inside a LinkedStack class
Slide 30:
For example, starting with an empty stack and pushing the strings "Alice" and "Bob" in succession will result in the scenario shown in this slide.
Slide 31:
A further operation of pushing "Carol" on the stack would give the result shown in this slide.
Slide 32:
All of the stack methods have straightforward implementations using linked lists.
Slide 33:
 
The LinkedStack class will have a field top that points to the item at the top of the stack and simultaneously serves as the head of the linked list. The stack will be empty whenever the expression top == null is true, so the empty method simply returns the value of that expression.


Slide 34:
The push operation adds a new item s to the front of the list.
Slide 35:
The pop method saves the value in the node at the top, removes the top node from the list by moving the head pointer past it, and returns the saved value
Slide 36:
The peek method returns the value field of the node at the front of the list. Both peek and pop throw an exception if they are called on an empty stack.

toString() Method

toString()方法

Finally, the LinkedStack class is equipped with a toString method that uses a StringBuilder object to create a string representation of the class. Having this method allows the contents of the entire stack st to be displayed by passing it to the System.out.print method:
System.out.println(st);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只萌新兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值