206. Reverse Linked List

Reverse a singly linked list.

Solution:

终于碰上这题了……想去年被网易 recruiter 鄙视唉
一次 AC~开心。

思路是 three pointers walk,旋转中间 current 指针指向的节点的 next 指针。注意 handle 好边界条件就行。

移动顺序是 pre = current,然后 current = post,最后 post = current.next。末尾的时候可能 current 会移到 null,之后判断一下 current 是否为 null,如果是则 break,不进行 post 指针的移动了(不然 NullPointerException了)。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution 
{
    public ListNode reverseList(ListNode head) 
    {
        ListNode pre = null;
        ListNode current = null;
        ListNode post = null;
        if(head == null)
            return null;
        else
        {
            current = head;
            post = current.next;
            while(true)
            {
                // reverse direction
                current.next = pre;
                
                // pointers walk
                pre = current;
                current = post;
                if(current == null)
                    break;
                post = current.next;
                
            }
            return pre;
        }
    }
}

你可能感兴趣的:(206. Reverse Linked List)