Detailed reversal linked list

Detailed reversal linked list

1. Problem solution

The code is as follows (example):


class Solution {
    
    
    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;
    }
}

2. Icon

No use without permission

3. Detailed

  • The first step: define the dummy node (null) and the head node (head) of the linked list.
  • Perform traversal: [traversal termination condition: cur = null]
    1>.nextTemp: point out the cue.next in the original linked list sequence [find out cur.next first to avoid getting it after the conversion point]
    2>. Conversion point: [call Cur.next conversion]
    3>. Move prev and cur to the position:
    [Move the position of prev first to avoid that cur cannot be found after moving]
  • Step 3: Return to prev

statement

  • Author: ELE (Yu Zuzu)
  • <Do not reprint without permission, welcome everyone to comment >

Guess you like

Origin blog.csdn.net/weixin_48557384/article/details/109246326