<?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/tag/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.4</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-69aff8ef93aa1721193063/]]]></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 2296 Design a Text Editor</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 03 Apr 2025 04:08:43 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10252</guid>

					<description><![CDATA[方法1：双向链表来存储文本，迭代器指向光标所在的位置。加一个dummy head会使代码简单很多。 时间复杂度：TextEditor O(1) addText O(&#124;text&#124;) deleteText O(k) cursorLeft O(k) cursorRight(k)空间复杂度：O(n) 由于每个字符需要创建一个节点（17+个字节），虽然没有超时，但实际工程中是不能使用这种方式的。 [crayon-69aff8ef94af9676167307/] 方法2: 用两个string来代表光标左边的字符串和光标右边的字符串。注：右边字符串是反转的。 左右两边的字符串只会增长（或者覆盖），不会缩短，这是用空间换时间。 删除的时候就是修改了长度而已，并没有缩短字符串，所以是O(1)的。如果缩短的话需则要O(k)时间，还要加上内存释放/再分配的时间，应该会慢一些但不多。 移动光标的时候，就是把左边字符串的最后k个copy到右边的最后面，或者反过来。同样没有缩短，只会变长。 时间复杂度: TextEditor O(1) addText O(&#124;text&#124;) deleteText O(1)&#8230;]]></description>
										<content:encoded><![CDATA[
<p>方法1：双向链表来存储文本，迭代器指向光标所在的位置。加一个dummy head会使代码简单很多。</p>



<p>时间复杂度：TextEditor O(1) addText O(|text|) deleteText O(k) cursorLeft O(k) cursorRight(k)<br>空间复杂度：O(n)</p>



<p>由于每个字符需要创建一个节点（17+个字节），虽然没有超时，但实际工程中是不能使用这种方式的。</p>



<pre class="urvanov-syntax-highlighter-plain-tag">// https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/
class TextEditor {
public:
  TextEditor(): data_{'$'}, cursor_{begin(data_)} {}
  
  void addText(string text) {
    for (char c : text)
      cursor_ = data_.insert(++cursor_, c);
  }
  
  int deleteText(int k) {
    for (int i = 0; i &lt; k; ++i) {
      if (cursor_ == begin(data_)) return i;
      data_.erase(cursor_--);
    }
    return k;
  }
  
  string cursorLeft(int k) {
    for (int i = 0; i &lt; k; ++i) {
      if (cursor_ == begin(data_)) break;
      cursor_--;
    }
    return getText();
  }
  
  string cursorRight(int k) {
    for (int i = 0; i &lt; k; ++i) {
      if (cursor_ == prev(end(data_))) break;
      cursor_++;
    }
    return getText();
  }
private:
  string getText() {
    string ans;
    auto it = cursor_;
    for (int i = 0; i &lt; 10; ++i) {
      if (it == begin(data_)) break;
      ans += *it--;
    }
    reverse(begin(ans), end(ans));
    return ans;
  }

  list&lt;char&gt; data_;
  list&lt;char&gt;::iterator cursor_;
};</pre>



<p>方法2: 用两个string来代表光标左边的字符串和光标右边的字符串。注：右边字符串是反转的。</p>



<p>左右两边的字符串只会增长（或者覆盖），不会缩短，这是用空间换时间。</p>



<p>删除的时候就是修改了长度而已，并没有缩短字符串，所以是O(1)的。<br>如果缩短的话需则要O(k)时间，还要加上内存释放/再分配的时间，应该会慢一些但不多。</p>



<p>移动光标的时候，就是把左边字符串的最后k个copy到右边的最后面，或者反过来。同样没有缩短，只会变长。</p>



<p>时间复杂度: TextEditor O(1) addText O(|text|) deleteText O(1) cursorLeft O(k) cursorRight(k)<br>空间复杂度：O(n)，n为构建的最长的字符串</p>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/Screenshot-2025-04-03-at-9.37.22 PM.png"><img fetchpriority="high" decoding="async" width="676" height="511" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/Screenshot-2025-04-03-at-9.37.22 PM.png" alt="" class="wp-image-10262" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/Screenshot-2025-04-03-at-9.37.22 PM.png 676w, https://zxi.mytechroad.com/blog/wp-content/uploads/2025/04/Screenshot-2025-04-03-at-9.37.22 PM-300x227.png 300w" sizes="(max-width: 676px) 100vw, 676px" /></a></figure>



<pre class="urvanov-syntax-highlighter-plain-tag">// https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/
class TextEditor {
public:
  TextEditor() {}
  
  void addText(string_view text) {
    ensureSize(l, m + text.size());
    copy(begin(text), end(text), begin(l) + m);
    m += text.size();
  }
  
  int deleteText(int k) {
    k = min(k, m);
    m -= k;
    return k;
  }
  
  string cursorLeft(int k) {
    ensureSize(r, n + k);
    for (k = min(k, m); k &gt; 0; --k)
      r[n++] = l[--m];
    return getText();
  }
  
  string cursorRight(int k) {
    ensureSize(l, m + k);
    for (k = min(k, n); k &gt; 0; --k)
      l[m++] = r[--n];
    return getText();
  }
private:
  inline void ensureSize(string&amp; s, int size) {
    if (s.size() &lt; size)
      s.resize(size);
  }

  string getText() const {
    return string(begin(l) + m - min(m, 10), begin(l) + m);
  }

  string l;
  string r;
  int m = 0;
  int n = 0;
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/string/leetcode-2296-design-a-text-editor/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 114. Flatten Binary Tree to Linked List</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-114-flatten-binary-tree-to-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-114-flatten-binary-tree-to-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 04:23:33 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8828</guid>

					<description><![CDATA[Given the&#160;root&#160;of a binary tree, flatten the tree into a &#8220;linked list&#8221;: The &#8220;linked list&#8221; should use the same&#160;TreeNode&#160;class where the&#160;right&#160;child pointer points to the&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>root</code>&nbsp;of a binary tree, flatten the tree into a &#8220;linked list&#8221;:</p>



<ul class="wp-block-list"><li>The &#8220;linked list&#8221; should use the same&nbsp;<code>TreeNode</code>&nbsp;class where the&nbsp;<code>right</code>&nbsp;child pointer points to the next node in the list and the&nbsp;<code>left</code>&nbsp;child pointer is always&nbsp;<code>null</code>.</li><li>The &#8220;linked list&#8221; should be in the same order as a&nbsp;<a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank" rel="noreferrer noopener"><strong>pre-order</strong><strong>&nbsp;traversal</strong></a>&nbsp;of the binary tree.</li></ul>



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



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



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



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



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



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



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



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



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



<p><strong>Follow up:</strong>&nbsp;Can you flatten the tree in-place (with&nbsp;<code>O(1)</code>&nbsp;extra space)?</p>



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



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



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

<pre class="urvanov-syntax-highlighter-plain-tag"># Author: Huahua
class Solution:
  def flatten(self, root: Optional[TreeNode]) -&amp;gt; None:
    &quot;&quot;&quot;
    Do not return anything, modify root in-place instead.
    &quot;&quot;&quot;
    def solve(root: Optional[TreeNode]):
      if not root: return None, None
      if not root.left and not root.right: return root, root
      l_head = l_tail = r_head = r_tail = None
      if root.left:
        l_head, l_tail = solve(root.left)
      if root.right:
        r_head, r_tail = solve(root.right)
      root.left = None
      root.right = l_head or r_head
      if l_tail:
        l_tail.right = r_head
      return root, r_tail or l_tail
    return solve(root)[0]</pre>
</div></div>



<p><strong>Solution 2: Unfolding</strong></p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag"># Author: Huahua
class Solution:
  def flatten(self, root: Optional[TreeNode]) -&gt; None:
    while root:
      if root.left:
        prev = root.left
        while prev.right: prev = prev.right
        prev.right = root.right
        root.right = root.left
        root.left = None
      root = root.right</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-114-flatten-binary-tree-to-linked-list/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 1823. Find the Winner of the Circular Game</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-1823-find-the-winner-of-the-circular-game/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-1823-find-the-winner-of-the-circular-game/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 13 Apr 2021 06:28:01 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[queue]]></category>
		<category><![CDATA[simulation]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8342</guid>

					<description><![CDATA[There are&#160;n&#160;friends that are playing a game. The friends are sitting in a circle and are numbered from&#160;1&#160;to&#160;n&#160;in&#160;clockwise order. More formally, moving clockwise from the&#160;ith&#160;friend&#8230;]]></description>
										<content:encoded><![CDATA[
<p>There are&nbsp;<code>n</code>&nbsp;friends that are playing a game. The friends are sitting in a circle and are numbered from&nbsp;<code>1</code>&nbsp;to&nbsp;<code>n</code>&nbsp;in&nbsp;<strong>clockwise order</strong>. More formally, moving clockwise from the&nbsp;<code>i<sup>th</sup></code>&nbsp;friend brings you to the&nbsp;<code>(i+1)<sup>th</sup></code>&nbsp;friend for&nbsp;<code>1 &lt;= i &lt; n</code>, and moving clockwise from the&nbsp;<code>n<sup>th</sup></code>&nbsp;friend brings you to the&nbsp;<code>1<sup>st</sup></code>&nbsp;friend.</p>



<p>The rules of the game are as follows:</p>



<ol class="wp-block-list"><li><strong>Start</strong>&nbsp;at the&nbsp;<code>1<sup>st</sup></code>&nbsp;friend.</li><li>Count the next&nbsp;<code>k</code>&nbsp;friends in the clockwise direction&nbsp;<strong>including</strong>&nbsp;the friend you started at. The counting wraps around the circle and may count some friends more than once.</li><li>The last friend you counted leaves the circle and loses the game.</li><li>If there is still more than one friend in the circle, go back to step&nbsp;<code>2</code>&nbsp;<strong>starting</strong>&nbsp;from the friend&nbsp;<strong>immediately clockwise</strong>&nbsp;of the friend who just lost and repeat.</li><li>Else, the last friend in the circle wins the game.</li></ol>



<p>Given the number of friends,&nbsp;<code>n</code>, and an integer&nbsp;<code>k</code>, return&nbsp;<em>the winner of the game</em>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, k = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Here are the steps of the game:
1) Start at friend 1.
2) Count 2 friends clockwise, which are friends 1 and 2.
3) Friend 2 leaves the circle. Next start is friend 3.
4) Count 2 friends clockwise, which are friends 3 and 4.
5) Friend 4 leaves the circle. Next start is friend 5.
6) Count 2 friends clockwise, which are friends 5 and 1.
7) Friend 1 leaves the circle. Next start is friend 3.
8) Count 2 friends clockwise, which are friends 3 and 5.
9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 6, k = 5
<strong>Output:</strong> 1
<strong>Explanation:</strong> The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= k &lt;= n &lt;= 500</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution 1: Simulation w/ Queue</strong> <strong>/ List</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua, 56 ms, 24.3 MB
class Solution {
public:
  int findTheWinner(int n, int k) {
    queue&lt;int&gt; q;
    for (int i = 1; i &lt;= n; ++i)
      q.push(i);
    
    while (q.size() != 1) {
      for (int i = 1; i &lt; k; ++i) {
        int x = q.front();
        q.pop();
        q.push(x);
      }
      q.pop();        
    }
    return q.front();
  }
};</pre>

</div><h2 class="tabtitle">C++/List</h2>
<div class="tabcontent">

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua, 12 ms, 6.8 MB
class Solution {
public:
  int findTheWinner(int n, int k) {
    list&lt;int&gt; l;
    for (int i = 1; i &lt;= n; ++i)
      l.push_back(i);
    
    auto it = l.begin();
    while (l.size() != 1) {
      for (int i = 1; i &lt; k; ++i)
        if (++it == l.end()) 
          it = l.begin();
      it = l.erase(it);
      if (it == l.end()) 
        it = l.begin();
    }
    return l.front();
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-1823-find-the-winner-of-the-circular-game/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>
	</channel>
</rss>
