Reverse Linked List

Reverse a singly linked list.

Note

  1. Create tail = null;

  2. Head loop through the list: Store head.next, head points to tail, tail becomes head, head goes to stored head.next;

  3. Return tail.

Solution

public class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode tail = null;
        while (head != null) {
            ListNode temp = head.next;
            head.next = tail;
            tail = head;
            head = temp;
        }
        return tail;
    }
}

Reverse Linked List II

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

Solution

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null) return null;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;
        int i = 0;
        while (i++ < m-1) {//注意这里,pre只要走到第m-1位
            pre = pre.next;
        }
        ListNode cur = pre.next;
        ListNode next = pre.next.next;
        for (i = 0; i < n-m; i++) {
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
            next = cur.next;
        }
        return dummy.next;
    }
}

linspiration
161 声望53 粉丝