206. 反转链表
一、Java
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return null;
ListNode pre = null, cur = head, next = head.next;
while (next != null) {
cur.next = pre;
pre = cur;
cur = next;
next = cur.next;
}
cur.next = pre;
return cur;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head, next;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode next = head.next, newHead = reverseList(next);
head.next = null;
next.next = head;
return newHead;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}