链式栈和链式队列的优点:不用像顺序栈和顺序队列一样,进行扩容。
链式栈
class LinkStack<T>{
private Entry
<T> bottom
;
private int count
;
public LinkStack(){
bottom
= new Entry<>(null
, null
);
}
public void push(T val
){
Entry
<T> node
= new Entry<>(val
, bottom
.next
);
bottom
.next
= node
;
count
++;
}
public T
pop(){
if(empty())
return null
;
T val
= bottom
.next
.data
;
bottom
.next
= bottom
.next
.next
;
count
--;
return val
;
}
public T
peek(){
if(empty())
return null
;
return bottom
.next
.data
;
}
public boolean empty(){
return bottom
.next
== null
;
}
public int size(){
return this.count
;
}
static class Entry<T>{
T data
;
Entry
<T> next
;
public Entry(T data
, Entry
<T> next
) {
this.data
= data
;
this.next
= next
;
}
}
}
public class LinkStackTest {
public static void main(String
[] args
) {
LinkStack
<Integer> ls
= new LinkStack<>();
ls
.push(23);
ls
.push(21);
ls
.push(56);
ls
.push(84);
while(!ls
.empty()){
System
.out
.print(ls
.pop() + " ");
}
System
.out
.println();
}
}
链式队列
class LinkQueue<T> {
private Entry
<T> front
;
private Entry
<T> rear
;
private int count
=0;
public LinkQueue() {
Entry
<T> node
=new Entry<>(null
,null
);
node
.next
=null
;
front
=rear
=node
;
}
public void offer(T val
) {
Entry
<T> node
= new Entry<>(val
, null
);
rear
.next
=node
;
rear
= node
;
count
++;
}
public T
poll() {
T val
= null
;
if(this.front
.next
!= null
){
val
= this.front
.next
.data
;
this.front
.next
= this.front
.next
.next
;
if(this.front
.next
== null
){
this.rear
= this.front
;
}
this.count
--;
}
return val
;
}
public T
peek() {
if (empty()) {
return null
;
}
return front
.next
.data
;
}
public boolean empty() {
return front
==rear
;
}
public int size(){
return this.count
;
}
public static class Entry<T> {
T data
;
Entry
<T> next
;
public Entry(T data
, Entry
<T> next
) {
this.data
= data
;
this.next
= next
;
}
}
}
转载请注明原文地址: https://yun.8miu.com/read-23376.html