實現單鏈表反轉應該有兩種思路,第一種是從首節點開始反轉,一直到尾節點結束,一種是從尾節點開始反轉,一直到首節點結束。
一、由首節點開始
如上圖所示,首先節點1與節點2發生發反轉,也就是節點2的next指向節點1,節點1因爲最終會變爲尾節點,所以其next置換爲null,此時節點3賦值於臨時變量。然後節點2與存儲了節點3的臨時變量發生反轉。然後節點3與儲存了節點4的臨時變量發生發轉。實現代碼如下
public class LinkedReversal {
public static class Node{
private int data;
private Node next;
public Node(int data){
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 void main(String[] args){
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
Node node4=new Node(4);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
Node tofrom=reversal(node1);
while(tofrom!=null){
System.out.println(tofrom.getData());
tofrom=tofrom.getNext();
}
}
//實現鏈表反轉
public static Node reversal(Node node){
if(node==null){
return null;
}
Node current=node;//記錄當前節點,此處爲首節點
Node next=node.getNext();//記錄下一節點,此處爲首節點的下一節點
current.setNext(null);//因爲反轉後鏈表的首節點變爲尾節點,所以要把首節點的下一節點置換爲null
while(next!=null){
Node tmp=next.getNext();//把next節點的下一節點存在臨時變量中,因爲next節點的下一節點會置換爲current
next.setNext(current);//實現鏈表反轉
//指針下移,繼續重複以上操作
current=next;
next=tmp;
}
return current;
}
}
二、由尾節點開始
首先遞歸到尾節點,然後尾節點4的next反轉指向節點3,3的next重置爲null,然後節點3的next反轉指向節點2,節點2的next重置爲null。然後節點2的next反轉指向1,1的next重置爲null。實現如下
public class LinkedReversal {
public static class Node{
private int data;
private Node next;
public Node(int data){
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 void main(String[] args){
Node node1=new Node(1);
Node node2=new Node(2);
Node node3=new Node(3);
Node node4=new Node(4);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
Node tofrom=reversal(node1);
while(tofrom!=null){
System.out.println(tofrom.getData());
tofrom=tofrom.getNext();
}
}
//實現鏈表反轉
public static Node reversal(Node current){
if(current==null||current.getNext()==null){
return current;
}
Node reNode=reversal(current.getNext());//一直遞歸到尾節點,然後依次返回
current.getNext().setNext(current);//當前節點的next反轉指向當前節點
current.setNext(null);//當前節點的next重置爲null
return reNode;
}
}