之面再补充图片~
1.迭代版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null) return null;//先特判头结点是否为null
ListNode a = head, b = head.next; //新建结点a、b分别指向头结点及头结点的下一节点
while(b != null){//当b不为null时循环操作
ListNode c = b.next; //要先记录b的下一结点,防止更改后丢失
b.next = a; //使b指向a
a = b; //a、b都后移一位
b = c;
}
head.next = null;//链表已反转完毕,将原头结点的下一结点置为null
return a; //返回现头结点
}
}
2.递归版本(代码结合画图更容易理解)
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;//若只有一个结点,不用反转直接返回
//建一新头结点
ListNode new_head = reverseList(head.next);//递归调用当前结点的下一结点进行反转
head.next.next = head; //调用反转结束后,当前头结点的下一结点已成尾结点,需要把当前头结点接到链表末尾
head.next = null; //并把当前头结点指向null
return new_head; //返回新的头结点
}
}