Reverse

206. Reverse Linked Listarrow-up-right

My Solutions:

Time: O(n); Space: O(1)

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode pre = null;
    while (head != null) {
        ListNode temp = head.next; // store next
        head.next = pre; // reverse current(head) node's pointer
        pre = head; // move pointers one position ahead
        head = temp;
    }
    return pre;
}
  • recursive version

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;
}

92. Reverse Linked List IIarrow-up-right

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 ≤ mn ≤ length of list.

My Solutions:

只反转从m到n位置的nodes,所以需要先走到m之前的位置,然后反转到n-m的位置

Time: O(n); Space: O(1)

25。Reverse Nodes in k-Group

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list's nodes, only nodes themselves may be changed.

Example 1:

Example 2:

My Solutions:

这道题和#92是类似的。

Last updated