<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>List &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/list/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Sat, 05 Apr 2025 20:23:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>List &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 430. Flatten a Multilevel Doubly Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-430-flatten-a-multilevel-doubly-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-430-flatten-a-multilevel-doubly-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 05 Apr 2025 20:20:38 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[doubly linked list]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[recurrsion]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10272</guid>

					<description><![CDATA[用递归实现比较简单一点。如果需要完美的one pass则需要写一个helper function，返回flattern后的head和tail. 注意这是双向链表，要把A把B连接到一起，需要同时改两个指针A->next = B, B->prev = A。 时间复杂度：O(n)空间复杂度：O(n) / stack [crayon-67f958bb1cfde715611302/]]]></description>
										<content:encoded><![CDATA[
<p>用递归实现比较简单一点。如果需要完美的one pass则需要写一个helper function，返回flattern后的head和tail.</p>



<p>注意这是双向链表，要把A把B连接到一起，需要同时改两个指针A->next = B, B->prev = A。</p>



<p>时间复杂度：O(n)<br>空间复杂度：O(n) / stack</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  Node* flatten(Node* head) {
    return solve(head).first;
  }
 private:
  // Flaten head, return new head and new tail.
  pair&lt;Node*, Node*&gt; solve(Node* head) {
    if (!head) return {nullptr, nullptr};
    Node dummy;
    Node* cur = &amp;dummy;
    cur-&gt;next = head;
    while (cur-&gt;next) {
      cur = cur-&gt;next;
      if (cur-&gt;child) {
        auto [h, t] = solve(cur-&gt;child);
        t-&gt;next = cur-&gt;next;
        h-&gt;prev = cur;
        if (cur-&gt;next) {
          cur-&gt;next-&gt;prev = t;
        }
        cur-&gt;next = h;
        cur-&gt;child = nullptr;
      }
    }
    return {dummy.next, cur};
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-430-flatten-a-multilevel-doubly-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2181. Merge Nodes in Between Zeros</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2181-merge-nodes-in-between-zeros/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2181-merge-nodes-in-between-zeros/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 02 Mar 2022 14:51:51 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[skip]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9522</guid>

					<description><![CDATA[You are given the&#160;head&#160;of a linked list, which contains a series of integers&#160;separated&#160;by&#160;0&#8216;s. The&#160;beginning&#160;and&#160;end&#160;of the linked list will have&#160;Node.val == 0. For&#160;every&#160;two consecutive&#160;0&#8216;s,&#160;merge&#160;all the nodes&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>head</code>&nbsp;of a linked list, which contains a series of integers&nbsp;<strong>separated</strong>&nbsp;by&nbsp;<code>0</code>&#8216;s. The&nbsp;<strong>beginning</strong>&nbsp;and&nbsp;<strong>end</strong>&nbsp;of the linked list will have&nbsp;<code>Node.val == 0</code>.</p>



<p>For&nbsp;<strong>every&nbsp;</strong>two consecutive&nbsp;<code>0</code>&#8216;s,&nbsp;<strong>merge</strong>&nbsp;all the nodes lying in between them into a single node whose value is the&nbsp;<strong>sum</strong>&nbsp;of all the merged nodes. The modified list should not contain any&nbsp;<code>0</code>&#8216;s.</p>



<p>Return&nbsp;<em>the</em>&nbsp;<code>head</code>&nbsp;<em>of the modified linked list</em>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [0,3,1,0,4,5,2,0]
<strong>Output:</strong> [4,11]
<strong>Explanation:</strong> 
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [0,1,0,3,0,2,2,0]
<strong>Output:</strong> [1,3,4]
<strong>Explanation:</strong> 
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in the list is in the range&nbsp;<code>[3, 2 * 10<sup>5</sup>]</code>.</li><li><code>0 &lt;= Node.val &lt;= 1000</code></li><li>There are&nbsp;<strong>no</strong>&nbsp;two consecutive nodes with&nbsp;<code>Node.val == 0</code>.</li><li>The&nbsp;<strong>beginning</strong>&nbsp;and&nbsp;<strong>end</strong>&nbsp;of the linked list have&nbsp;<code>Node.val == 0</code>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: List</strong></h2>



<p>Skip the first zero, replace every zero node with the sum of values of its previous nodes.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* mergeNodes(ListNode* head) {
    ListNode dummy;    
    head = head-&gt;next;
    for (ListNode* prev = &amp;dummy; head; head = head-&gt;next) {
      int sum = 0;
      while (head-&gt;val != 0) {
        sum += head-&gt;val;
        head = head-&gt;next;
      }
      prev-&gt;next = head;
      head-&gt;val = sum;
      prev = head;      
    }
    return dummy.next;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-2181-merge-nodes-in-between-zeros/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2130. Maximum Twin Sum of a Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 Jan 2022 11:40:22 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9415</guid>

					<description><![CDATA[In a linked list of size&#160;n, where&#160;n&#160;is&#160;even, the&#160;ith&#160;node (0-indexed) of the linked list is known as the&#160;twin&#160;of the&#160;(n-1-i)th&#160;node, if&#160;0 &#60;= i &#60;= (n / 2)&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In a linked list of size&nbsp;<code>n</code>, where&nbsp;<code>n</code>&nbsp;is&nbsp;<strong>even</strong>, the&nbsp;<code>i<sup>th</sup></code>&nbsp;node (<strong>0-indexed</strong>) of the linked list is known as the&nbsp;<strong>twin</strong>&nbsp;of the&nbsp;<code>(n-1-i)<sup>th</sup></code>&nbsp;node, if&nbsp;<code>0 &lt;= i &lt;= (n / 2) - 1</code>.</p>



<ul class="wp-block-list"><li>For example, if&nbsp;<code>n = 4</code>, then node&nbsp;<code>0</code>&nbsp;is the twin of node&nbsp;<code>3</code>, and node&nbsp;<code>1</code>&nbsp;is the twin of node&nbsp;<code>2</code>. These are the only nodes with twins for&nbsp;<code>n = 4</code>.</li></ul>



<p>The&nbsp;<strong>twin sum&nbsp;</strong>is defined as the sum of a node and its twin.</p>



<p>Given the&nbsp;<code>head</code>&nbsp;of a linked list with even length, return&nbsp;<em>the&nbsp;<strong>maximum twin sum</strong>&nbsp;of the linked list</em>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [5,4,2,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong>
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
There are no other nodes with twins in the linked list.
Thus, the maximum twin sum of the linked list is 6. 
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [4,2,2,3]
<strong>Output:</strong> 7
<strong>Explanation:</strong>
The nodes with twins present in this linked list are:
- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
Thus, the maximum twin sum of the linked list is max(7, 4) = 7. 
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,100000]
<strong>Output:</strong> 100001
<strong>Explanation:</strong>
There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in the list is an&nbsp;<strong>even</strong>&nbsp;integer in the range&nbsp;<code>[2, 10<sup>5</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Two Pointers + Reverse List</strong></h2>



<p>Use fast slow pointers to find the middle point and reverse the second half.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int pairSum(ListNode* head) {
    auto reverse = [](ListNode* head, ListNode* prev = nullptr) {
      while (head) {
        swap(head-&gt;next, prev);
        swap(head, prev);
      }
      return prev;
    };
    
    ListNode* fast = head;
    ListNode* slow = head;
    while (fast) {
      fast = fast-&gt;next-&gt;next;
      slow = slow-&gt;next;
    }
    
    slow = reverse(slow);
    int ans = 0;
    while (slow) {
      ans = max(ans, head-&gt;val + slow-&gt;val);
      head = head-&gt;next;
      slow = slow-&gt;next;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2095. Delete the Middle Node of a Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2095-delete-the-middle-node-of-a-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2095-delete-the-middle-node-of-a-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Dec 2021 06:24:18 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[middle]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9020</guid>

					<description><![CDATA[You are given the&#160;head&#160;of a linked list.&#160;Delete&#160;the&#160;middle node, and return&#160;the&#160;head&#160;of the modified linked list. The&#160;middle node&#160;of a linked list of size&#160;n&#160;is the&#160;⌊n / 2⌋th&#160;node from&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>head</code>&nbsp;of a linked list.&nbsp;<strong>Delete</strong>&nbsp;the&nbsp;<strong>middle node</strong>, and return&nbsp;<em>the</em>&nbsp;<code>head</code>&nbsp;<em>of the modified linked list</em>.</p>



<p>The&nbsp;<strong>middle node</strong>&nbsp;of a linked list of size&nbsp;<code>n</code>&nbsp;is the&nbsp;<code>⌊n / 2⌋<sup>th</sup></code>&nbsp;node from the&nbsp;<strong>start</strong>&nbsp;using&nbsp;<strong>0-based indexing</strong>, where&nbsp;<code>⌊x⌋</code>&nbsp;denotes the largest integer less than or equal to&nbsp;<code>x</code>.</p>



<ul class="wp-block-list"><li>For&nbsp;<code>n</code>&nbsp;=&nbsp;<code>1</code>,&nbsp;<code>2</code>,&nbsp;<code>3</code>,&nbsp;<code>4</code>, and&nbsp;<code>5</code>, the middle nodes are&nbsp;<code>0</code>,&nbsp;<code>1</code>,&nbsp;<code>1</code>,&nbsp;<code>2</code>, and&nbsp;<code>2</code>, respectively.</li></ul>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,3,4,7,1,2,6]
<strong>Output:</strong> [1,3,4,1,2,6]
<strong>Explanation:</strong>
The above figure represents the given linked list. The indices of the nodes are written below.
Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
We return the new list after removing this node. 
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,3,4]
<strong>Output:</strong> [1,2,4]
<strong>Explanation:</strong>
The above figure represents the given linked list.
For n = 4, node 2 with value 3 is the middle node, which is marked in red.
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [2,1]
<strong>Output:</strong> [2]
<strong>Explanation:</strong>
The above figure represents the given linked list.
For n = 2, node 1 with value 1 is the middle node, which is marked in red.
Node 0 with value 2 is the only node remaining after removing node 1.</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in the list is in the range&nbsp;<code>[1, 10<sup>5</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Fast / Slow pointers</strong></h2>



<p>Use fast / slow pointers to find the previous node of the middle one, then skip the middle one.</p>



<p>prev.next = prev.next.next</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  ListNode* deleteMiddle(ListNode* head) {
    ListNode dummy(0, head);
    ListNode* prev = &amp;dummy;
    ListNode* fast = head;
    // prev points to the previous node of the middle one.
    while (fast &amp;&amp; fast-&gt;next) {
      prev = prev-&gt;next;
      fast = fast-&gt;next-&gt;next;
    }    
    prev-&gt;next = prev-&gt;next-&gt;next;
    return dummy.next;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-2095-delete-the-middle-node-of-a-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 143. Reorder List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 07:08:40 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[fast slow]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8926</guid>

					<description><![CDATA[You are given the head of a singly linked-list. The list can be represented as: L0 → L1 → … → Ln - 1 →&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the head of a singly linked-list. The list can be represented as:</p>



<pre class="wp-block-preformatted;crayon:false">L<sub>0</sub> → L<sub>1</sub> → … → L<sub>n - 1</sub> → L<sub>n</sub>
</pre>



<p><em>Reorder the list to be on the following form:</em></p>



<pre class="wp-block-preformatted;crayon:false">L<sub>0</sub> → L<sub>n</sub> → L<sub>1</sub> → L<sub>n - 1</sub> → L<sub>2</sub> → L<sub>n - 2</sub> → …
</pre>



<p>You may not modify the values in the list&#8217;s nodes. Only nodes themselves may be changed.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,3,4]
<strong>Output:</strong> [1,4,2,3]
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,3,4,5]
<strong>Output:</strong> [1,5,2,4,3]
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in the list is in the range&nbsp;<code>[1, 5 * 10<sup>4</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 1000</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Three steps</strong></h2>



<p>Step 1: Find mid node that splits the list into two halves.<br>Step 2: Reverse the second half<br>Step 3: Merge two lists</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  void reorderList(ListNode* head) {
    if (!head || !head-&gt;next) return;
    ListNode* slow = head;
    ListNode* fast = head;            

    while (fast-&gt;next &amp;&amp; fast-&gt;next-&gt;next) {
      slow = slow-&gt;next;
      fast = fast-&gt;next-&gt;next;          
    }
    
    ListNode* h1 = head;
    ListNode* h2 = reverse(slow-&gt;next);
    slow-&gt;next = nullptr;

    while (h1 &amp;&amp; h2) {
      ListNode* n1 = h1-&gt;next;
      ListNode* n2 = h2-&gt;next;
      h1-&gt;next = h2;
      h2-&gt;next = n1;
      h1 = n1;
      h2 = n2;
    }
  }
private:       
  // reverse a linked list
  // returns head of the linked list
  ListNode* reverse(ListNode* head) {
    if (!head || !head-&gt;next) return head;

    ListNode* prev = head;
    ListNode* cur = head-&gt;next;
    ListNode* next = cur;
    while (cur) {
      next = next-&gt;next;
      cur-&gt;next = prev;
      prev = cur;
      cur = next;
    }

    head-&gt;next = nullptr;
    return prev;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-143-reorder-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 147. Insertion Sort List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-147-insertion-sort-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-147-insertion-sort-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 06:48:33 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[insertion]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8922</guid>

					<description><![CDATA[Given the&#160;head&#160;of a singly linked list, sort the list using&#160;insertion sort, and return&#160;the sorted list&#8217;s head. The steps of the&#160;insertion sort&#160;algorithm: Insertion sort iterates, consuming&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>head</code>&nbsp;of a singly linked list, sort the list using&nbsp;<strong>insertion sort</strong>, and return&nbsp;<em>the sorted list&#8217;s head</em>.</p>



<p>The steps of the&nbsp;<strong>insertion sort</strong>&nbsp;algorithm:</p>



<ol class="wp-block-list"><li>Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.</li><li>At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.</li><li>It repeats until no input elements remain.</li></ol>



<p>The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.</p>



<figure class="wp-block-image"><img decoding="async" src="https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif" alt=""/></figure>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/04/sort1linked-list.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [4,2,1,3]
<strong>Output:</strong> [1,2,3,4]
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/04/sort2linked-list.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [-1,5,3,4,0]
<strong>Output:</strong> [-1,0,3,4,5]
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in the list is in the range&nbsp;<code>[1, 5000]</code>.</li><li><code>-5000 &lt;= Node.val &lt;= 5000</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Scan from head</strong></h2>



<p>For each node, scan from head of the list to find the insertion position in O(n), and adjust pointers.</p>



<p>Time complexity: O(n<sup>2</sup>)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* insertionSortList(ListNode* head) {
    ListNode dummy;
    
    while (head) {
      ListNode* iter = &amp;dummy;
      while (iter-&gt;next &amp;&amp; head-&gt;val &gt; iter-&gt;next-&gt;val)
        iter = iter-&gt;next;
      ListNode* next = head-&gt;next;
      head-&gt;next = iter-&gt;next;
      iter-&gt;next = head;
      head = next;
    }
    
    return dummy.next;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-147-insertion-sort-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 160. Intersection of Two Linked Lists</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-160-intersection-of-two-linked-lists/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-160-intersection-of-two-linked-lists/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 22:10:04 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[intersection]]></category>
		<category><![CDATA[list]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8873</guid>

					<description><![CDATA[Given the heads of two singly linked-lists&#160;headA&#160;and&#160;headB, return&#160;the node at which the two lists intersect. If the two linked lists have no intersection at all,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the heads of two singly linked-lists&nbsp;<code>headA</code>&nbsp;and&nbsp;<code>headB</code>, return&nbsp;<em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return&nbsp;<code>null</code>.</p>



<p>For example, the following two linked lists begin to intersect at node&nbsp;<code>c1</code>:</p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/05/160_statement.png" alt=""/></figure>



<p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p>



<p><strong>Note</strong>&nbsp;that the linked lists must&nbsp;<strong>retain their original structure</strong>&nbsp;after the function returns.</p>



<p><strong>Custom Judge:</strong></p>



<p>The inputs to the&nbsp;<strong>judge</strong>&nbsp;are given as follows (your program is&nbsp;<strong>not</strong>&nbsp;given these inputs):</p>



<ul class="wp-block-list"><li><code>intersectVal</code>&nbsp;&#8211; The value of the node where the intersection occurs. This is&nbsp;<code>0</code>&nbsp;if there is no intersected node.</li><li><code>listA</code>&nbsp;&#8211; The first linked list.</li><li><code>listB</code>&nbsp;&#8211; The second linked list.</li><li><code>skipA</code>&nbsp;&#8211; The number of nodes to skip ahead in&nbsp;<code>listA</code>&nbsp;(starting from the head) to get to the intersected node.</li><li><code>skipB</code>&nbsp;&#8211; The number of nodes to skip ahead in&nbsp;<code>listB</code>&nbsp;(starting from the head) to get to the intersected node.</li></ul>



<p>The judge will then create the linked structure based on these inputs and pass the two heads,&nbsp;<code>headA</code>&nbsp;and&nbsp;<code>headB</code>&nbsp;to your program. If you correctly return the intersected node, then your solution will be&nbsp;<strong>accepted</strong>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image;crayon:false"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
<strong>Output:</strong> Intersected at '8'
<strong>Explanation:</strong> The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image;crayon:false"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
<strong>Output:</strong> Intersected at '2'
<strong>Explanation:</strong> The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
<strong>Output:</strong> No intersection
<strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes of&nbsp;<code>listA</code>&nbsp;is in the&nbsp;<code>m</code>.</li><li>The number of nodes of&nbsp;<code>listB</code>&nbsp;is in the&nbsp;<code>n</code>.</li><li><code>0 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li><li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= skipA &lt;= m</code></li><li><code>0 &lt;= skipB &lt;= n</code></li><li><code>intersectVal</code>&nbsp;is&nbsp;<code>0</code>&nbsp;if&nbsp;<code>listA</code>&nbsp;and&nbsp;<code>listB</code>&nbsp;do not intersect.</li><li><code>intersectVal == listA[skipA] == listB[skipB]</code>&nbsp;if&nbsp;<code>listA</code>&nbsp;and&nbsp;<code>listB</code>&nbsp;intersect.</li></ul>



<p><strong>Follow up:</strong>&nbsp;Could you write a solution that runs in&nbsp;<code>O(n)</code>&nbsp;time and use only&nbsp;<code>O(1)</code>&nbsp;memory?</p>



<p></p>



<h2 class="wp-block-heading"><strong>Solution 1: Two Passes by swapping heads</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    if (!headA || !headB) return nullptr;
    ListNode* a = headA;
    ListNode* b = headB;
    while (a != b) {
      a = a ? a-&gt;next : headB;
      b = b ? b-&gt;next : headA;
    }
    return a;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-160-intersection-of-two-linked-lists/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 142. Linked List Cycle II</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-142-linked-list-cycle-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-142-linked-list-cycle-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 21:23:00 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[cycle]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8862</guid>

					<description><![CDATA[Given the&#160;head&#160;of a linked list, return&#160;the node where the cycle begins. If there is no cycle, return&#160;null. There is a cycle in a linked list&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>head</code>&nbsp;of a linked list, return&nbsp;<em>the node where the cycle begins. If there is no cycle, return&nbsp;</em><code>null</code>.</p>



<p>There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the&nbsp;<code>next</code>&nbsp;pointer. Internally,&nbsp;<code>pos</code>&nbsp;is used to denote the index of the node that tail&#8217;s&nbsp;<code>next</code>&nbsp;pointer is connected to (<strong>0-indexed</strong>). It is&nbsp;<code>-1</code>&nbsp;if there is no cycle.&nbsp;<strong>Note that</strong>&nbsp;<code>pos</code>&nbsp;<strong>is not passed as a parameter</strong>.</p>



<p><strong>Do not modify</strong>&nbsp;the linked list.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [3,2,0,-4], pos = 1
<strong>Output:</strong> tail connects to node index 1
<strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the second node.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2], pos = 0
<strong>Output:</strong> tail connects to node index 0
<strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the first node.
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1], pos = -1
<strong>Output:</strong> no cycle
<strong>Explanation:</strong> There is no cycle in the linked list.
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of the nodes in the list is in the range&nbsp;<code>[0, 10<sup>4</sup>]</code>.</li><li><code>-10<sup>5</sup>&nbsp;&lt;= Node.val &lt;= 10<sup>5</sup></code></li><li><code>pos</code>&nbsp;is&nbsp;<code>-1</code>&nbsp;or a&nbsp;<strong>valid index</strong>&nbsp;in the linked-list.</li></ul>



<p><strong>Follow up:</strong>&nbsp;Can you solve it using&nbsp;<code>O(1)</code>&nbsp;(i.e. constant) memory?</p>



<p></p>



<h2 class="wp-block-heading"><strong>Solution 1: Hashtset</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode *detectCycle(ListNode *head) {
    unordered_set&lt;ListNode*&gt; s;
    for (ListNode* cur = head; cur; cur = cur-&gt;next)
      if (!s.insert(cur).second) return cur;
    return nullptr;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution: Fast slow pointers</strong></h2>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode *detectCycle(ListNode *head) {
    unordered_set&lt;ListNode*&gt; s;
    for (ListNode* cur = head; cur; cur = cur-&gt;next)
      if (!s.insert(cur).second) return cur;
    return nullptr;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-142-linked-list-cycle-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 109. Convert Sorted List to Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-109-convert-sorted-list-to-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-109-convert-sorted-list-to-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 03:51:03 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8825</guid>

					<description><![CDATA[Given the&#160;head&#160;of a singly linked list where elements are&#160;sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>head</code>&nbsp;of a singly linked list where elements are&nbsp;<strong>sorted in ascending order</strong>, convert it to a height balanced BST.</p>



<p>For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of&nbsp;<em>every</em>&nbsp;node never differ by more than 1.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2020/08/17/linked.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [-10,-3,0,5,9]
<strong>Output:</strong> [0,-3,9,-10,null,5]
<strong>Explanation:</strong> One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = []
<strong>Output:</strong> []
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [0]
<strong>Output:</strong> [0]
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,3]
<strong>Output:</strong> [3,1]
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in&nbsp;<code>head</code>&nbsp;is in the range&nbsp;<code>[0, 2 * 10<sup>4</sup>]</code>.</li><li><code>-10<sup>5</sup>&nbsp;&lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution 1: Recursion w/ Fast + Slow Pointers</strong></h2>



<p>For each sublist, use fast/slow pointers to find the mid and build the tree.</p>



<p>Time complexity: O(nlogn)<br>Space complexity: O(logn)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  TreeNode *sortedListToBST(ListNode *head) {
    function&lt;TreeNode*(ListNode*, ListNode*)&gt; build 
      = [&amp;](ListNode* head, ListNode* tail) -&gt; TreeNode* {
      if (!head || head == tail) return nullptr;
      ListNode *fast = head, *slow = head;
      while (fast != tail &amp;&amp; fast-&gt;next != tail) {
        slow = slow-&gt;next;
        fast = fast-&gt;next-&gt;next;
      }
      TreeNode *root = new TreeNode(slow-&gt;val);
      root-&gt;left = build(head, slow);
      root-&gt;right = build(slow-&gt;next, tail);
      return root;
    };
    return build(head, nullptr);
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-109-convert-sorted-list-to-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2074. Reverse Nodes in Even Length Groups</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2074-reverse-nodes-in-even-length-groups/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2074-reverse-nodes-in-even-length-groups/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 15 Nov 2021 18:52:13 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8712</guid>

					<description><![CDATA[You are given the&#160;head&#160;of a linked list. The nodes in the linked list are&#160;sequentially&#160;assigned to&#160;non-empty&#160;groups whose lengths form the sequence of the natural numbers (1,&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>head</code>&nbsp;of a linked list.</p>



<p>The nodes in the linked list are&nbsp;<strong>sequentially</strong>&nbsp;assigned to&nbsp;<strong>non-empty</strong>&nbsp;groups whose lengths form the sequence of the natural numbers (<code>1, 2, 3, 4, ...</code>). The&nbsp;<strong>length</strong>&nbsp;of a group is the number of nodes assigned to it. In other words,</p>



<ul class="wp-block-list"><li>The&nbsp;<code>1<sup>st</sup></code>&nbsp;node is assigned to the first group.</li><li>The&nbsp;<code>2<sup>nd</sup></code>&nbsp;and the&nbsp;<code>3<sup>rd</sup></code>&nbsp;nodes are assigned to the second group.</li><li>The&nbsp;<code>4<sup>th</sup></code>,&nbsp;<code>5<sup>th</sup></code>, and&nbsp;<code>6<sup>th</sup></code>&nbsp;nodes are assigned to the third group, and so on.</li></ul>



<p>Note that the length of the last group may be less than or equal to&nbsp;<code>1 + the length of the second to last group</code>.</p>



<p><strong>Reverse</strong>&nbsp;the nodes in each group with an&nbsp;<strong>even</strong>&nbsp;length, and return&nbsp;<em>the</em>&nbsp;<code>head</code>&nbsp;<em>of the modified linked list</em>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/25/eg1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [5,2,6,3,9,1,7,3,8,4]
<strong>Output:</strong> [5,6,2,3,9,1,4,8,3,7]
<strong>Explanation:</strong>
- The length of the first group is 1, which is odd, hence no reversal occurrs.
- The length of the second group is 2, which is even, hence the nodes are reversed.
- The length of the third group is 3, which is odd, hence no reversal occurrs.
- The length of the last group is 4, which is even, hence the nodes are reversed.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/25/eg2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,1,0,6]
<strong>Output:</strong> [1,0,1,6]
<strong>Explanation:</strong>
- The length of the first group is 1. No reversal occurrs.
- The length of the second group is 2. The nodes are reversed.
- The length of the last group is 1. No reversal occurrs.
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/28/eg3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [2,1]
<strong>Output:</strong> [2,1]
<strong>Explanation:</strong>
- The length of the first group is 1. No reversal occurrs.
- The length of the last group is 1. No reversal occurrs.
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [8]
<strong>Output:</strong> [8]
<strong>Explanation:</strong> There is only one group whose length is 1. No reversal occurrs.
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in the list is in the range&nbsp;<code>[1, 10<sup>5</sup>]</code>.</li><li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: List</strong></h2>



<p>Reuse ReverseList from<a href="https://zxi.mytechroad.com/blog/list/leetcode-206-reverse-linked-list/" data-type="post" data-id="2044"> 花花酱 LeetCode 206. Reverse Linked List</a></p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  ListNode* reverseEvenLengthGroups(ListNode* head) {
    ListNode dummy(0, head);
    ListNode* prev = &amp;dummy;
    auto reverse = [](ListNode* head) {     
      ListNode* prev = nullptr;
      while (head) {
        ListNode* next = head-&gt;next;
        head-&gt;next = prev;
        prev = head;
        head = next;
      }
      return prev;
    };
    
    for (int k = 1; head; ++k) {
      ListNode* tail = head;
      int l = 1;
      while (l &lt; k &amp;&amp; tail &amp;&amp; tail-&gt;next) {
        tail = tail-&gt;next;
        ++l;
      }
      ListNode* next = tail-&gt;next;
      if (l % 2 == 0) {
        tail-&gt;next = nullptr;
        prev-&gt;next = reverse(head);
        head-&gt;next = next;
        prev = head;        
        head = head-&gt;next;
      } else {
        prev = tail;
        head = next;
      }
    }
    return dummy.next;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-2074-reverse-nodes-in-even-length-groups/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>LeetCode 2058. Find the Minimum and Maximum Number of Nodes Between Critical Points</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Nov 2021 06:48:43 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8664</guid>

					<description><![CDATA[A&#160;critical point&#160;in a linked list is defined as&#160;either&#160;a&#160;local maxima&#160;or a&#160;local minima. A node is a&#160;local maxima&#160;if the current node has a value&#160;strictly greater&#160;than the previous&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A&nbsp;<strong>critical point</strong>&nbsp;in a linked list is defined as&nbsp;<strong>either</strong>&nbsp;a&nbsp;<strong>local maxima</strong>&nbsp;or a&nbsp;<strong>local minima</strong>.</p>



<p>A node is a&nbsp;<strong>local maxima</strong>&nbsp;if the current node has a value&nbsp;<strong>strictly greater</strong>&nbsp;than the previous node and the next node.</p>



<p>A node is a&nbsp;<strong>local minima</strong>&nbsp;if the current node has a value&nbsp;<strong>strictly smaller</strong>&nbsp;than the previous node and the next node.</p>



<p>Note that a node can only be a local maxima/minima if there exists&nbsp;<strong>both</strong>&nbsp;a previous node and a next node.</p>



<p>Given a linked list&nbsp;<code>head</code>, return&nbsp;<em>an array of length 2 containing&nbsp;</em><code>[minDistance, maxDistance]</code><em>&nbsp;where&nbsp;</em><code>minDistance</code><em>&nbsp;is the&nbsp;<strong>minimum distance</strong>&nbsp;between&nbsp;<strong>any&nbsp;two distinct</strong>&nbsp;critical points and&nbsp;</em><code>maxDistance</code><em>&nbsp;is the&nbsp;<strong>maximum distance</strong>&nbsp;between&nbsp;<strong>any&nbsp;two distinct</strong>&nbsp;critical points. If there are&nbsp;<strong>fewer</strong>&nbsp;than two critical points, return&nbsp;</em><code>[-1, -1]</code>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/13/a1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [3,1]
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> There are no critical points in [3,1].
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/13/a2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [5,3,1,2,5,1,2]
<strong>Output:</strong> [1,3]
<strong>Explanation:</strong> There are three critical points:
- [5,3,<strong><u>1</u></strong>,2,5,1,2]: The third node is a local minima because 1 is less than 3 and 2.
- [5,3,1,2,<strong>5</strong>,1,2]: The fifth node is a local maxima because 5 is greater than 2 and 1.
- [5,3,1,2,5,<strong>1</strong>,2]: The sixth node is a local minima because 1 is less than 5 and 2.
The minimum distance is between the fifth and the sixth node. minDistance = 6 - 5 = 1.
The maximum distance is between the third and the sixth node. maxDistance = 6 - 3 = 3.
</pre>



<p><strong>Example 3:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/14/a5.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,3,2,2,3,2,2,2,7]
<strong>Output:</strong> [3,3]
<strong>Explanation:</strong> There are two critical points:
- [1,<strong>3</strong>,2,2,3,2,2,2,7]: The second node is a local maxima because 3 is greater than 1 and 2.
- [1,3,2,2,<strong>3</strong>,2,2,2,7]: The fifth node is a local maxima because 3 is greater than 2 and 2.
Both the minimum and maximum distances are between the second and the fifth node.
Thus, minDistance and maxDistance is 5 - 2 = 3.
Note that the last node is not considered a local maxima because it does not have a next node.
</pre>



<p><strong>Example 4:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/10/13/a4.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [2,3,3,2]
<strong>Output:</strong> [-1,-1]
<strong>Explanation:</strong> There are no critical points in [2,3,3,2].
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in the list is in the range&nbsp;<code>[2, 10<sup>5</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: One Pass</strong></h2>



<p>Track the first and last critical points.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; nodesBetweenCriticalPoints(ListNode* head) {    
    ListNode* p = nullptr;
    int min_dist = INT_MAX;
    int max_dist = INT_MIN;    
    for (int i = 0, l = -1, r = -1; head; ++i, p = head, head = head-&gt;next) {
      if (p &amp;&amp; head-&gt;next) {
        if ((head-&gt;val &gt; p-&gt;val &amp;&amp; head-&gt;val &gt; head-&gt;next-&gt;val) 
            || (head-&gt;val &lt; p-&gt;val &amp;&amp; head-&gt;val &lt; head-&gt;next-&gt;val)) {
          if (r != -1) {
            min_dist = min(min_dist, i - r);
            max_dist = max(max_dist, i - l);
          } else {
            l = i;
          }          
          r = i;          
        }
      }
    }
    return { min_dist == INT_MAX ? -1 : min_dist, 
             max_dist == INT_MIN ? -1 : max_dist };
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-2058-find-the-minimum-and-maximum-number-of-nodes-between-critical-points/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1721. Swapping Nodes in a Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-1721-swapping-nodes-in-a-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-1721-swapping-nodes-in-a-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Jan 2021 17:59:01 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[swap]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7964</guid>

					<description><![CDATA[You are given the&#160;head&#160;of a linked list, and an integer&#160;k. Return&#160;the head of the linked list after&#160;swapping&#160;the values of the&#160;kth&#160;node from the beginning and the&#160;kth&#160;node&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given the&nbsp;<code>head</code>&nbsp;of a linked list, and an integer&nbsp;<code>k</code>.</p>



<p>Return&nbsp;<em>the head of the linked list after&nbsp;<strong>swapping</strong>&nbsp;the values of the&nbsp;</em><code>k<sup>th</sup></code>&nbsp;<em>node from the beginning and the&nbsp;</em><code>k<sup>th</sup></code>&nbsp;<em>node from the end (the list is&nbsp;<strong>1-indexed</strong>).</em></p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [1,4,3,2,5]
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [7,9,6,6,7,8,3,0,9,5], k = 5
<strong>Output:</strong> [7,9,6,6,8,7,3,0,9,5]
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1], k = 1
<strong>Output:</strong> [1]
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2], k = 1
<strong>Output:</strong> [2,1]
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,3], k = 2
<strong>Output:</strong> [1,2,3]
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li>The number of nodes in the list is&nbsp;<code>n</code>.</li><li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= Node.val &lt;= 100</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution:</strong></h2>



<p>Two passes. First pass, find the length of the list. Second pass, record the k-th and n-k+1-th node.<br>Once done swap their values.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  ListNode* swapNodes(ListNode* head, int k) {
    int l = 0;
    ListNode* cur = head;    
    while (cur) { cur = cur-&gt;next; ++l; }    
    
    cur = head;
    ListNode* n1 = nullptr;
    ListNode* n2 = nullptr;
    for (int i = 1; i &lt;= l; ++i, cur = cur-&gt;next) {
      if (i == k) n1 = cur;
      if (i == l - k + 1) n2 = cur;
    }
    swap(n1-&gt;val, n2-&gt;val);
    return head;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-1721-swapping-nodes-in-a-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1670. Design Front Middle Back Queue</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-1670-design-front-middle-back-queue/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-1670-design-front-middle-back-queue/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 28 Nov 2020 20:00:04 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[list]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7725</guid>

					<description><![CDATA[Design a queue that supports&#160;push&#160;and&#160;pop&#160;operations in the front, middle, and back. Implement the&#160;FrontMiddleBack&#160;class: FrontMiddleBack()&#160;Initializes the queue. void pushFront(int val)&#160;Adds&#160;val&#160;to the&#160;front&#160;of the queue. void pushMiddle(int val)&#160;Adds&#160;val&#160;to&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Design a queue that supports&nbsp;<code>push</code>&nbsp;and&nbsp;<code>pop</code>&nbsp;operations in the front, middle, and back.</p>



<p>Implement the&nbsp;<code>FrontMiddleBack</code>&nbsp;class:</p>



<ul class="wp-block-list"><li><code>FrontMiddleBack()</code>&nbsp;Initializes the queue.</li><li><code>void pushFront(int val)</code>&nbsp;Adds&nbsp;<code>val</code>&nbsp;to the&nbsp;<strong>front</strong>&nbsp;of the queue.</li><li><code>void pushMiddle(int val)</code>&nbsp;Adds&nbsp;<code>val</code>&nbsp;to the&nbsp;<strong>middle</strong>&nbsp;of the queue.</li><li><code>void pushBack(int val)</code>&nbsp;Adds&nbsp;<code>val</code>&nbsp;to the&nbsp;<strong>back</strong>&nbsp;of the queue.</li><li><code>int popFront()</code>&nbsp;Removes the&nbsp;<strong>front</strong>&nbsp;element of the queue and returns it. If the queue is empty, return&nbsp;<code>-1</code>.</li><li><code>int popMiddle()</code>&nbsp;Removes the&nbsp;<strong>middle</strong>&nbsp;element of the queue and returns it. If the queue is empty, return&nbsp;<code>-1</code>.</li><li><code>int popBack()</code>&nbsp;Removes the&nbsp;<strong>back</strong>&nbsp;element of the queue and returns it. If the queue is empty, return&nbsp;<code>-1</code>.</li></ul>



<p><strong>Notice</strong>&nbsp;that when there are&nbsp;<strong>two</strong>&nbsp;middle position choices, the operation is performed on the&nbsp;<strong>frontmost</strong>&nbsp;middle position choice. For example:</p>



<ul class="wp-block-list"><li>Pushing&nbsp;<code>6</code>&nbsp;into the middle of&nbsp;<code>[1, 2, 3, 4, 5]</code>&nbsp;results in&nbsp;<code>[1, 2,&nbsp;6, 3, 4, 5]</code>.</li><li>Popping the middle from&nbsp;<code>[1, 2,&nbsp;3, 4, 5, 6]</code>&nbsp;returns&nbsp;<code>3</code>&nbsp;and results in&nbsp;<code>[1, 2, 4, 5, 6]</code>.</li></ul>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong>
["FrontMiddleBackQueue", "pushFront", "pushBack", "pushMiddle", "pushMiddle", "popFront", "popMiddle", "popMiddle", "popBack", "popFront"]
[[], [1], [2], [3], [4], [], [], [], [], []]
<strong>Output:</strong>
[null, null, null, null, null, 1, 3, 4, 2, -1]
<strong>Explanation:</strong>
FrontMiddleBackQueue q = new FrontMiddleBackQueue();
q.pushFront(1);   // [1]
q.pushBack(2);    // [1, 2]
q.pushMiddle(3);  // [1, 3, 2]
q.pushMiddle(4);  // [1, 4, 3, 2]
q.popFront();     // return 1 -&gt; [4, 3, 2]
q.popMiddle();    // return 3 -&gt; [4, 2]
q.popMiddle();    // return 4 -&gt; [2]
q.popBack();      // return 2 -&gt; []
q.popFront();     // return -1 -&gt; [] (The queue is empty)
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li><code>1 &lt;= val &lt;= 10<sup>9</sup></code></li><li>At most&nbsp;<code>1000</code>&nbsp;calls will be made to&nbsp;<code>pushFront</code>,&nbsp;<code>pushMiddle</code>,&nbsp;<code>pushBack</code>,&nbsp;<code>popFront</code>,&nbsp;<code>popMiddle</code>, and&nbsp;<code>popBack</code>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: List + Middle Iterator</strong></h2>



<p>Time complexity: O(1) per op<br>Space complexity: O(n) in total</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class FrontMiddleBackQueue {
public:
  FrontMiddleBackQueue() {}

  void pushFront(int val) {
    q_.push_front(val); 
    updateMit(even() ? -1 : 0);
  }

  void pushMiddle(int val) {    
    if (q_.empty())
      q_.push_back(val);
    else
      q_.insert(even() ? next(mit_) : mit_, val);
    updateMit(even() ? -1 : 1);
  }

  void pushBack(int val) {    
    q_.push_back(val); 
    updateMit(even() ? 0 : 1);
  }

  int popFront() {     
    if (q_.empty()) return -1;
    int val = q_.front();
    q_.pop_front();
    updateMit(even() ? 0 : 1);
    return val;
  }

  int popMiddle() {    
    if (q_.empty()) return -1;
    int val = *mit_;
    mit_ = q_.erase(mit_);
    updateMit(even() ? -1 : 0);
    return val;
  }

  int popBack() {    
    if (q_.empty()) return -1;
    int val = q_.back();
    q_.pop_back();
    updateMit(even() ? -1 : 0);
    return val;
  }
private:  
  void updateMit(int delta) {
    if (q_.size() &lt;= 1) {      
      mit_ = begin(q_);
    } else {
      if (delta &gt; 0) ++mit_;
      if (delta &lt; 0) --mit_;
    }    
  }
  
  bool even() const { return q_.size() % 2 == 0; }
  
  list&lt;int&gt; q_;
  list&lt;int&gt;::iterator mit_;
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-1670-design-front-middle-back-queue/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1669. Merge In Between Linked Lists</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-1669-merge-in-between-linked-lists/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-1669-merge-in-between-linked-lists/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 28 Nov 2020 19:07:25 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[dummy head]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prev]]></category>
		<category><![CDATA[tail]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7722</guid>

					<description><![CDATA[You are given two linked lists:&#160;list1&#160;and&#160;list2&#160;of sizes&#160;n&#160;and&#160;m&#160;respectively. Remove&#160;list1&#8216;s nodes from the&#160;ath&#160;node to the&#160;bth&#160;node, and put&#160;list2&#160;in their place. The blue edges and nodes in the following&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two linked lists:&nbsp;<code>list1</code>&nbsp;and&nbsp;<code>list2</code>&nbsp;of sizes&nbsp;<code>n</code>&nbsp;and&nbsp;<code>m</code>&nbsp;respectively.</p>



<p>Remove&nbsp;<code>list1</code>&#8216;s nodes from the&nbsp;<code>a<sup>th</sup></code>&nbsp;node to the&nbsp;<code>b<sup>th</sup></code>&nbsp;node, and put&nbsp;<code>list2</code>&nbsp;in their place.</p>



<p>The blue edges and nodes in the following figure incidate the result:</p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2020/11/05/fig1.png" alt=""/></figure>



<p><em>Build the result list and return its head.</em></p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> list1 = [0,1,2,3,4,5], a = 3, b = 4, list2 = [1000000,1000001,1000002]
<strong>Output:</strong> [0,1,2,1000000,1000001,1000002,5]
<strong>Explanation:</strong> We remove the nodes 3 and 4 and put the entire list2 in their place. The blue edges and nodes in the above figure indicate the result.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2020/11/05/merge_linked_list_ex2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> list1 = [0,1,2,3,4,5,6], a = 2, b = 5, list2 = [1000000,1000001,1000002,1000003,1000004]
<strong>Output:</strong> [0,1,1000000,1000001,1000002,1000003,1000004,6]
<strong>Explanation:</strong> The blue edges and nodes in the above figure indicate the result.
</pre>



<p><strong>Constraints:</strong></p>



<ul class="wp-block-list"><li><code>3 &lt;= list1.length &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= a &lt;= b &lt; list1.length - 1</code></li><li><code>1 &lt;= list2.length &lt;= 10<sup>4</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: List Operations</strong></h2>



<p>Find the following nodes:<br>1. previous node to the a-th node: prev_a<br>2. the b-th node: node_b<br>3. tail node of list2: tail2<br><br>prev_a-&gt;next = list2<br>tail2-&gt;next = node_b<br><br>return list1</p>



<p>Time complexity: O(m+n)<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* mergeInBetween(ListNode* list1, int a, int b, ListNode* list2) {
    ListNode dummy(0, list1);
    ListNode* prev_a = &amp;dummy;
    for (int i = 0; i &lt; a; ++i) prev_a = prev_a-&gt;next;
    ListNode* node_b = prev_a-&gt;next;
    for (int i = a; i &lt;= b; ++i) node_b = node_b-&gt;next;
    ListNode* tail2 = list2;
    while (tail2-&gt;next) tail2 = tail2-&gt;next;
    
    prev_a-&gt;next = list2;    
    tail2-&gt;next = node_b;
    return list1;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-1669-merge-in-between-linked-lists/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 61. Rotate List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-61-rotate-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-61-rotate-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 29 Oct 2020 05:59:44 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[node]]></category>
		<category><![CDATA[rotate]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7573</guid>

					<description><![CDATA[Given a linked&#160;list, rotate the list to the right by&#160;k&#160;places, where&#160;k&#160;is non-negative. Example 1: Input: 1-&#62;2-&#62;3-&#62;4-&#62;5-&#62;NULL, k = 2 Output: 4-&#62;5-&#62;1-&#62;2-&#62;3-&#62;NULL Explanation: rotate 1 steps&#8230;]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 61. Rotate List - 刷题找工作 EP365" width="500" height="281" src="https://www.youtube.com/embed/a4XZu2VVE9Q?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Given a linked&nbsp;list, rotate the list to the right by&nbsp;<em>k</em>&nbsp;places, where&nbsp;<em>k</em>&nbsp;is non-negative.</p>



<p><strong>Example 1:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL, k = 2
<strong>Output:</strong> 4-&gt;5-&gt;1-&gt;2-&gt;3-&gt;NULL
<strong>Explanation:</strong>
rotate 1 steps to the right: 5-&gt;1-&gt;2-&gt;3-&gt;4-&gt;NULL
rotate 2 steps to the right: 4-&gt;5-&gt;1-&gt;2-&gt;3-&gt;NULL
</pre>



<p><strong>Example 2:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> 0-&gt;1-&gt;2-&gt;NULL, k = 4
<strong>Output:</strong> <code>2-&gt;0-&gt;1-&gt;NULL</code>
<strong>Explanation:</strong>
rotate 1 steps to the right: 2-&gt;0-&gt;1-&gt;NULL
rotate 2 steps to the right: 1-&gt;2-&gt;0-&gt;NULL
rotate 3 steps to the right:&nbsp;<code>0-&gt;1-&gt;2-&gt;NULL</code>
rotate 4 steps to the right:&nbsp;<code>2-&gt;0-&gt;1-&gt;NULL</code></pre>



<h2 class="wp-block-heading"><strong>Solution: Find the prev of the new head</strong></h2>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/61-ep365.png" alt="" class="wp-image-7576" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/61-ep365.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/61-ep365-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/10/61-ep365-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Step 1: Get the tail node T while counting the length of the list.<br>Step 2: k %= l, k can be greater than l, rotate k % l times has the same effect.<br>Step 3: Find the previous node P of the new head N by moving (l &#8211; k &#8211; 1) steps from head<br>Step 4: set P.next to null, T.next to head and return N</p>



<p>Time complexity: O(n) n is the length of the list<br>Space complexity: O(1)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* rotateRight(ListNode* head, int k) {
    if (!head) return head;    
    int l = 1;
    ListNode* tail = head;
    while (tail-&gt;next) { tail = tail-&gt;next; ++l; }
    k %= l;
    if (k == 0) return head;
    
    ListNode* prev = head;
    while (--l &gt; k) prev = prev-&gt;next;
    ListNode* new_head = prev-&gt;next;
    tail-&gt;next = head;
    prev-&gt;next = nullptr;
    return new_head;
  }
};</pre>

</div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">/**
 * 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 rotateRight(ListNode head, int k) {
    if (head == null) return null;
    int l = 1;
    ListNode tail = head;
    while (tail.next != null) {
      tail = tail.next;
      ++l;
    }
    k %= l;
    if (k == 0) return head;
    
    ListNode prev = head;
    for (int i = 0; i &lt; l - k - 1; ++i) {
      prev = prev.next;
    }
    
    ListNode new_head = prev.next;
    prev.next = null;
    tail.next = head;
    return new_head;
  }
}</pre>

</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution:
  def rotateRight(self, head: ListNode, k: int) -&gt; ListNode:
    if not head: return head
    tail = head
    l = 1
    while tail.next: 
      tail = tail.next
      l += 1
    k = k % l
    if k == 0: return head
    
    prev = head
    for _ in range(l - k - 1): prev = prev.next
    
    new_head = prev.next
    tail.next = head
    prev.next = None
    return new_head</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/list/leetcode-61-rotate-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
