//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) {
// 把所有的指针反向
ListNode pre = null;
ListNode cur = head;
ListNode temp = null;// 保存cur的下一个节点
while (cur != null) {
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
class Solution {
ListNode reverse(ListNode pre, ListNode cur) {
if (cur == null) {
return pre;
}
ListNode temp = cur.next;
cur.next = pre;
return reverse(cur, temp);
}
public ListNode reverseList(ListNode head) {
// 把所有的指针反向
return reverse(null,head);
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null)//链表本身为空
return null;
if (head.next == null)//为了找到翻转之后的头节点
return head;
ListNode last = reverseList(head.next);
// 反转指针
head.next.next = head;
head.next = null;//对中间节点无效 为了链表的原始头节点准备的
return last;
}
}
直接看官方解做的
每次循环或者迭代只翻转一个指针
要把反转之后的头节点找到