[Sword refers to offer] Reverse linked list (Interview with Ali)

Title description
Input a linked list, after inverting the linked list, output the header of the new linked list.
Example 1

输入
{
    
    1,2,3}
返回值
{
    
    3,2,1}

Solution
Take 3 nodes as an example:

  1. Use pre to record the previous node of the current node

  2. Use next to record the next node of the current node

  3. Define a new node cur and assign it to head

    The current node a is not empty, enter the loop, first record the next node position of a next = b; then let the pointer of a point to
    the position of pre and cur, just because the position of the next node is just recorded, so the linked list Without breaking, we let cur go to the position of b.
    The current node is that b is not empty, first record the position of the next node, let b point to the position of pre, that is, the position of a, and move pre and head. The
    current node c is not empty, record the position of the next node, and let c point to b , Move pre and cur at the same time, at this time cur is empty, jump out, and return to pre.

public class Solution {
    
    
    public ListNode ReverseList(ListNode head) {
    
    
        if(head == null || head.next == null) {
    
    
            return head;
        }
        ListNode cur = head;
        ListNode pre = null;
        ListNode next = null;
        while(cur != null) {
    
    
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

Guess you like

Origin blog.csdn.net/qq_45621376/article/details/114554091