[Double pointer] 206. Reverse linked list

206. Reverse Linked List

problem solving ideas

  • Define three pointers, cur pre temp
  • cur points to the current node, then pre points to the node before cur, and temp saves the next node of cur
  • Because you need to change the direction of cur, you need temp
  • Finally return pre is to return the new head node
/**
 * Definition for singly-linked list.
 * 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; }
 * }
 */
class Solution {
    
    
    public ListNode reverseList(ListNode head) {
    
    
        // 创建三个指针
        ListNode temp;
        ListNode pre = null;
        ListNode cur = head;

        // 使用快慢指针
        while(cur != null){
    
    
            // 先使用temp保存cur.next
            temp = cur.next;
            cur.next = pre;// 指向前面的节点
            pre = cur;// 移动pre指针
            cur = temp;// 移动cur指针
        }

        return pre;// 返回新的head

    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/131676545