生活随笔
收集整理的這篇文章主要介紹了
顺序栈,链栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
棧與鏈棧
- 一,順序棧
- 1.1 IStack棧接口
- 1.2,順序棧增刪改查的實現
- 1.3,測試順序棧
- 二,鏈棧
- 2.1,存放數據的結點
- 2.2,鏈棧的實現
- 2.3測試鏈棧
一,順序棧
1.1 IStack棧接口
public interface IStack {public void clear();public boolean isEmpty();public int length();public Object
peek(); public void push(Object x
); public Object
pop(); public void display();
}
1.2,順序棧增刪改查的實現
public class SeqStack implements IStack {private Object
[] stackElem
; private int top
; private int maxSize
; public SeqStack(int maxSize
) {top
= 0;this.maxSize
= maxSize
;stackElem
= new Object[maxSize
];}public void clear() {top
= 0; }public boolean isEmpty() {return top
== 0;}public int length() {return top
;}public Object
peek() {if (!isEmpty())return stackElem
[top
- 1];return null
;}public void push(Object x
) {if (top
== maxSize
) {System
.out
.println("棧已滿");return;}stackElem
[top
] = x
;top
++;}@Overridepublic Object
pop() {if (!isEmpty()) {top
--;return stackElem
[top
];}return null
;}public void display() {for (int i
= top
- 1; i
>= 0; i
--) {System
.out
.print(stackElem
[i
] + " "); }System
.out
.println();}}
1.3,測試順序棧
public
class TestSeqStack {public static void main
(String
[] args
) {SeqStack seqStack
= new SeqStack
(3);seqStack
.push
("abc");seqStack
.push
("def");seqStack
.push
("ghi");// 返回棧頂元素Object peekEle
= seqStack
.peek
();System
.out
.println
("棧頂元素" + peekEle
);// 出棧seqStack
.pop
();System
.out
.println
("出棧后:");// 遍歷棧seqStack
.display
();}}
/**
棧頂元素ghi
出棧后:
def abc
*/
二,鏈棧
2.1,存放數據的結點
public class Node {public Object data
; public Node next
; public Node() {this(null
, null
);}public Node(Object data
) {this(data
, null
);}public Node(Object data
, Node next
) {this.data
= data
;this.next
= next
;}
}
2.2,鏈棧的實現
public class LinearStack implements IStack {private Node top
; @Overridepublic void clear() {top
= null
;}@Overridepublic boolean isEmpty() {return top
== null
;}@Overridepublic int length() {Node p
= top
;int length
= 0;while (p
!= null
) {p
= p
.next
;length
++;}return length
;}@Overridepublic Object
peek() {if (!isEmpty())return top
.data
;return null
;}@Overridepublic void push(Object x
) {Node s
= new Node(x
);s
.next
= top
;top
= s
;}@Overridepublic Object
pop() {if (isEmpty()) {return null
;}Node p
= top
;top
= top
.next
; return p
.data
;}@Overridepublic void display() {Node p
= top
; while (p
!= null
) {System
.out
.print(p
.data
+ "\t");p
= p
.next
;}}}
2.3測試鏈棧
public class TestLinearStack {public static void main(String
[] args
) {LinearStack ls
= new LinearStack();ls
.push(1);ls
.push(3);ls
.push(5);ls
.push(7);System
.out
.println("棧頂元素:" + ls
.peek());System
.out
.println("出棧元素:" + ls
.pop());ls
.display();}}
總結
以上是生活随笔為你收集整理的顺序栈,链栈的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。