一、簡介
經查閱,主要有兩種方法實現鏈表反轉,遞歸反轉法和遍歷反轉法;
遞歸: 在反轉當前結點之前先反轉其后邊的結點,即、從尾結點開始逆向反轉各個節點的指針域指向;
遍歷:從前往后反轉各個結點的指針域的指向。
二、實現
定義一個結點類:
public class Node {
private int data; //數據域
private Node next; //指針域
public Node(int data) {
super();
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
遞歸反轉:
public static Node reverse(Node head){
//如果是空鏈表或者尾結點
if (head==null||head.getNext()==null) {
return head;
}
//先反轉后續結點
Node reversedHead=reverse(head.getNext());
//當前結點指針指向前一結點
head.getNext().setNext(head);
//令前一結點的指針域為null
head.setNext(null);
return reversedHead;
}
遍歷反轉:
public static Node reverse1(Node head){
if (head==null) {
return head;
}
//上一結點
Node pre=head;
//當前結點
Node cur=head.getNext();
//用於存儲下一節點
Node tem;
//cur==null 即尾結點
while(cur!=null){
//下一節點存入臨時結點
tem=cur.getNext();
//將當前結點指針指向上一節點
cur.setNext(pre);
//移動指針
pre=cur;
cur=tem;
}
head.setNext(null);
return pre;
}
