接下来让我们看看,如何利用单链表结构来实现栈与队列。由于栈的操作只限于栈顶元素,而单链表只有对首元素才能在O(1)时间内完成插入和删除,故这里把单链表的首节点作为栈顶,其余元素依次排列。此外,为了保证getSize()方法也能够在O(1)时间内完成,还需借助一个实例变量来动态记录栈中元素的数目。具体的实现如 代码二.12 所示。
Node类 Java代码见( Java 实现链表)
StackLink 类:
package com.list.stack;
import java.util.Arrays;
import com.stack.ExceptionStackEmpty;
import com.list.stack.Node;
public class StackList {
//Declared size of stack list
private static int size;
//Declared element
private static Node top;
public StackList() {
this.size = 0;
this.top = null;
}
// Get the size of stack
public int getSize() {
if(isEmpty())
return 0;
else
return size;
}
// Get whether stack is empty
public boolean isEmpty() {
return size == 0;
}
// Get the top element of stack
public Object top() throws ExceptionStackEmpty {
if(isEmpty())
throw new ExceptionStackEmpty("Stack is empty!");
return top.getElement();
}
// Push element to stack
public void push(Object element){
Node newNode = new Node(element,top);
top = newNode;
size ++;
}
// Pop element from stack
public Object pop() throws ExceptionStackEmpty {
if(isEmpty())
throw new ExceptionStackEmpty("Stack is empty!");
Object container = top.getElement();
top = top.getNext();
size --;
return container;
}
// Get the all elements of stack
public void getAllElements() throws ExceptionStackEmpty {
Node travelTop;
travelTop = top;
Object[] array = new Object[getSize()];
for(int i = 0;i < array.length;i ++ ){
array[i] = travelTop.getElement();
travelTop = travelTop.getNext();
}
System.out.println("Get all elemnt: " + Arrays.toString(array));
}
}
StackLinkTest 类:
package com.list.stack;
import com.stack.ExceptionStackEmpty;
public class StackListTest {
public static void main(String[] args) throws ExceptionStackEmpty {
//Test Class StackList
StackList sl = new StackList();
System.out.println("Size of stack list: " + sl.getSize());
System.out.println("Is emplty? : " + sl.isEmpty());
sl.push(12);
sl.push(13);
sl.push(15);
sl.push(17);
sl.push(2);
sl.push(6);
sl.getAllElements();
System.out.println("Size of stack list: " + sl.getSize());
System.out.println("Is emplty? : " + sl.isEmpty());
//sl.getAllElements();
System.out.println(sl.pop());
System.out.println(sl.pop());
System.out.println(sl.pop());
System.out.println(sl.pop());
System.out.println(sl.pop());
System.out.println(sl.pop());
System.out.println("Size of stack list: " + sl.getSize());
System.out.println("Is emplty? : " + sl.isEmpty());
}
}
测试结果:
Size of stack list: 0
Is emplty? : true
Get all elemnt: [6, 2, 17, 15, 13, 12]
Size of stack list: 6
Is emplty? : false
6
2
17
15
13
12
Size of stack list: 0
Is emplty? : true
转载请注明出处,谢谢!
http://blog.csdn.net/github_27609763/article/details/46476917
时间: 2024-10-02 20:54:18