实现单链表反转应该有两种思路,第一种是从首节点开始反转,一直到尾节点结束,一种是从尾节点开始反转,一直到首节点结束。
一、由首节点开始
如上图所示,首先节点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;
}
}