当前位置:网站首页>LeetCode——24. Exchange the nodes in the linked list in pairs (three pointers)

LeetCode——24. Exchange the nodes in the linked list in pairs (three pointers)

2022-06-11 16:50:00 Always--Learning

Title Description

image.png

Their thinking

  1. Define a pre node , Its next Domain points to head.
  2. Define a temporary pointer to pre.
  3. As long as the current node and the next node of the current node are not empty , Then enter the cycle .
  4. After entering the cycle , First save the next node of the current pointer .
  5. pre Point to next.
  6. cur.next = next.next;
  7. next.next = cur;
  8. pre = cur;
  9. cur = cur.next;

AC Code

var swapPairs = function(head) {
    
  //  The core of the node in the pairwise exchange linked list is to change through three pointers 
  if (!head) return null;
  let pre = new ListNode('-');
  pre.next = head;
  let temp = pre;
  let cur = head;
  while (cur && cur.next) {
    
    let next = cur.next  
    pre.next = next;
    cur.next = next.next;
    next.next = cur;
    pre = cur;
    cur = cur.next;
  }
  return temp.next;
};

reflection

The title of the linked list class seems simple , It's not , There are a lot of linked list problems that burn your brain , Especially if you just don't want to paint , Many ideas can only be drawn by hand , I soon knew how to do it , But it's hard to figure it out just in your head , So be sure to draw pictures . There are many similar topics , For example, reverse linked list ,K A group of flipped lists are common questions in the interview .

Icon

origin_img_v2_51bdacca-c48a-445c-b5d4-bfbc67259e6g.png

What is more difficult to think about is that in the process of moving pre and cur Who is it pointing to , Once we understand the direction of both of them, we can solve this problem , As long as the topic can be clarified , Similar problems such as list turnover will be solved , It is suggested to practice this kind of topic more , Almost all such topics involve pre,cur and next, there next It is often necessary to define... In a loop .

Reference link

原网站

版权声明
本文为[Always--Learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111623300439.html