在Java中實現鏈表是非常簡單的,每個節點都有一個值,然後把它鏈接到下一個節點。
定義節點:
class Node {
int val;
Node next;
Node(int x) {
val = x;
next = null;
}
}
棧結構(注意箭頭方向):
class Stack{
Node top;
public Node peek(){
if(top != null){
return top;
}
return null;
}
public Node pop(){
if(top == null){
return null;
}else{
Node temp = new Node(top.val);
top = top.next;
return temp;
}
}
public void push(Node n){
if(n != null){
n.next = top;
top = n;
}
}
}
隊列(Queue)前端(front)進行刪除操作,而在表的後端(rear)進行插入操作
class Queue{
Node first, last;
public void enqueue(Node n){
if(first == null){
first = n;
last = first;
}else{
last.next = n;
last = n;
}
}
public Node dequeue(){
if(first == null){
return null;
}else{
Node temp = new Node(first.val);
first = first.next;
return temp;
}
}
}
值得一提的是,Java標準庫中已經包含一個叫做Stack的類,鏈表也可以作爲一個隊列使用(add()和remove())。(鏈表實現隊列接口)如果你在面試過程中,需要用到棧或隊列解決問題時,你可以直接使用它們。