avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

24.Two or two exchanges linked watches

  2024-01-01        
字数统计: 89字   |   阅读时长: 1min

topic:

Give you a linked list,Two or two exchanges are adjacent nodes,And return to the head node of the linked list after exchange。You must complete this question without modifying the internal value of the node(Right now,Can only exchange nodes)。

Exemplary example 1:

enter:head = [1,2,3,4]
Output:[2,1,4,3]

Exemplary example 2:

enter:head = []
Output:[]

Exemplary example 3:

enter:head = [1]
Output:[1]

hint:

  • The number of nodes in the linked list is in the range [0, 100] Inside
  • 0 <= Node.val <= 100
Related Topics
  • recursion
  • Linked

  • 👍 1785
  • 👎 0
  • 24.Two or two exchanges linked watches.md

    Thought:

    use head 表示原始Linked的头节点,新的Linked的第二个节点,use newHead 表示新的Linked的头节点,原始Linked的第二个节点,则原始Linked中的其余节点的头节点是 newHead.next。make head.next = swapPairs(newHead.next),Indicates two or two exchanges for the rest of the nodes,The new head node after the exchange is head The next node。然后make newHead.next = head,Right now完成了所有节点的交换。最后返回新的Linked的头节点 newHead。
    recursion.gif

    Code:

    1
    2
    3
    4
    5
    6
    7
    8
    class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
    if not head or not head.next:
    return head
    virtual_head = head.next
    head.next = self.swapPairs(virtual_head.next)
    virtual_head.next = head
    return virtual_head
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class Solution {
    public:
    ListNode* swapPairs(ListNode* head) {
    if (head == nullptr or head->next == nullptr){
    return head;
    }
    ListNode *yummyNode = head->next;
    head->next = swapPairs(yummyNode->next);
    yummyNode->next = head;
    return yummyNode;
    }
    };
    • Python
    • answer

    扫一扫,分享到微信

    微信分享二维码
    2527.Query arrayXorBeautiful value Zhou Sai Third Question
    2639. Query the width of each column in the grid diagram
    目录
    1. 1. topic:
    2. 2. Thought:
    3. 3. Code:

    150 篇 | 131.7k
    次 | 人
    这里自动载入天数这里自动载入时分秒
    2022-2025 loong loong | 新南威尔士龙龙号