Java interview questions ------ reverse list

reward:

  • 1. The node list consists of two parts, a part of the current information is stored, pointing to another portion of the storage node to the next
  • 2. recursive implementation is really hard to understand, much more optimistic times

Reverse a singly linked list.

Example:

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

Here Insert Picture Description
Analysis: To reverse transcription of this list, become necessary after the front, the front becomes the back, so finding ways to reverse the front and back, then reversed judge to determine whether the condition has become curr is empty because relatively speaking , curr went to the front
Here Insert Picture Description

  • Iterative implementation
public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    while (curr != null) {
        ListNode nextTemp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;
}
  • Recursive

Understand: ListNode p = reverseList(head.next);
This line means that -> will head the list reversal, p represents the tail of the list after the reversal, that is reversed before the head of the list, head.next.next=headis the list points to the reverse, head.next=nullit is to point forward to cut off .

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;
}
Published 87 original articles · won praise 7 · views 5024

Guess you like

Origin blog.csdn.net/y18791050779/article/details/105060640