Reverse Linked List

Reverse a linked list.

Example

For linked list1->2->3, the reversed linked list is3->2->1

Solution: iterative

public ListNode reverse(ListNode head) {
    if(head == null || head.next == null) {
        return head;
    }
    ListNode pre = null;
    while(head != null) {
        ListNode second = head.next;
        head.next = pre;
        pre = head;
        head = second;
    }
    return pre;
}

Solution: recursive.

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

Reverse Linked List II

Reverse a linked list from position m to n.

Notice

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

Example

Given1->2->3->4->5->NULL, m =2and n =4, return1->4->3->2->5->NULL.

public ListNode reverseBetween(ListNode head, int m , int n) {
    if(head == null || head.next == null) {
        return head;
    }
    ListNode dummy = new ListNode(-1);
    dummy.next = head;
    ListNode pre = dummy;
    for(int i = 0; i < m - 1; i++) {
        pre = pre.next;
    }
    ListNode nhead = pre.next, second = nhead.next;
    for(int i = m; i < n; i++) {
        nhead.next = second.next;
        second.next = pre.next;
        pre.next = second;
        second = nhead.next;
    }
    return dummy.next;
}

results matching ""

    No results matching ""