LeetCode Singly Linked List - Sword Pointer Offer II 024. Reverse Linked List (Recursion and Iteration)

Address: https://leetcode.cn/problems/UHnkqh/
insert image description here
Problem-solving idea (iteration):
When traversing the linked list, change the next pointer of the current node to point to the previous node. Since the node does not refer to its previous node, it must be Store its previous node. Before changing the reference, the latter node also needs to be stored, and finally the new head reference is returned.

public class 反转链表_迭代 {
    
    
    public class ListNode {
    
    
      int val;
      ListNode next;
      ListNode() {
    
    }
      ListNode(int val) {
    
     this.val = val; }
      ListNode(int val, ListNode next) {
    
     this.val = val; this.next = next; }
  }
    public ListNode reverseList(ListNode head) {
    
    
        ListNode prev = null;
        ListNode curr = head;

        while (curr !=null){
    
    
            //next是当前节点的指针
            ListNode next = curr.next;
            //当前节点的指针指向上一个节点 并且存储在变量中.
            curr.next = prev;
            //上一个节点就是当前节点
            prev = curr;
            curr = next;
        }
        //最后
        return prev;
    }
}

Implemented recursively:

public class 反转链表_递归 {
    
    
    public class ListNode {
    
    
        int val;
        ListNode next;
        ListNode() {
    
    }
        ListNode(int val) {
    
     this.val = val; }
        ListNode(int val, ListNode next) {
    
     this.val = val; this.next = next; }
    }
    public ListNode reverseList(ListNode head) {
    
    
        //为了不陷入死循环
        if (head ==null || head.next ==null) return head;
        ListNode newHead = reverseList(head.next);
        //假如head=5 那么head.next是4 让4的指针指向5
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}

Guess you like

Origin blog.csdn.net/m0_62491934/article/details/128739263