描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
分析
指针移动
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
}
递归解法
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode dummy = reverseList(head.next);
ListNode pre = dummy;
while(pre.next != null){
pre = pre.next;
}
pre.next = head;
//要注意把当前的结点的后继赋为空,否则递归回到上一层,遍历的时候会陷入死循环。
head.next = null;
return dummy;
}
}
用图片理解反转代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null){
return head;
}
ListNode dummy = new ListNode(0);
ListNode pre = dummy;
dummy.next = head;
ListNode cur = head;
//循环判断条件不能是cur != null,否则当cur.next为空,temp.next会报错
while(cur.next != null){
ListNode temp = cur.next;
cur.next = temp.next;
temp.next = pre.next;
pre.next = temp;
}
//为cur的next赋空
cur.next = null;
return dummy.next;
}
}