206. Reverse Linked List

Reverse a singly linked list. Example

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

题意:如题目所讲。反转链表。这个是链表题中的重中之重。

代码

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) return null;
        ListNode prev = null, next = null, cur = head;
        while(cur != null) {
            next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }
}

Recursion 版本

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}

Search

    Table of Contents