StarryNights

每一个你所后悔的现在,都有一个不够努力的曾经

站内检索

循着字句,邂逅星光

搜索文章标题与正文,直达命中的章节

开始一次轻盈的站内探索

从这些主题开始探索

输入关键词

可同时输入多个词语缩小范围

发现内容

在摘要中查看高亮的关键词

快速直达

点击文章或章节标题继续阅读

# 引言

题目链接:https://leetcode.com/problems/swap-nodes-in-pairs/

# 题目大意

将链表中的节点两两交换。

  • Example

Given 1->2->3->4, you should return the list as 2->1->4->3.

Hint:

Your algorithm should use only constant extra space.

You may not modify the values in the list's nodes, only nodes itself may be changed.

即不可采取交换节点的方式, 同时保证空间复杂度为常数级别

# 题解

# 一句话题解

直接一张图说明, 定义一个无效空头结点便于统一化操作

SwapNodesInPairs

# 复杂度

时间复杂度 O(n)

空间复杂度 O(1)

# AC代码

c++版本

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution
{
  public:
    ListNode *swapPairs(ListNode *head)
    {

        ListNode *ret = new ListNode(-1);
        ret->next = head;
        ListNode *pre = ret;
        ListNode *cur = head;
        while (nullptr != cur && nullptr != cur->next)
        {
            pre->next = cur->next;
            cur->next = pre->next->next;
            pre->next->next = cur;
            pre = cur;
            cur = cur->next;
        }
        return ret->next;
    }
};

go版本

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

func swapPairs(head *ListNode) *ListNode {
	ret := &ListNode{-1, nil}
	ret.Next = head
	pre, cur := ret, head
	for nil != cur && nil != cur.Next {
		pre.Next = cur.Next
		cur.Next = pre.Next.Next
		pre.Next.Next = cur
		pre = cur
		cur = cur.Next
	}
	return ret.Next
}
更新于 阅读次数 — 次
STARRY NIGHTSPERSONAL NOTES

赞赏

文章至此,故事还在继续。

Seiun

长按或右键保存收款码

文章关联

1 篇关联

顺着引用的连线,读见篇章交错的脉络

展开关系图

拖动平移 · Ctrl / ⌘ + 滚轮缩放 · 点击节点阅读使用 + / − 按钮缩放 · 放大视图后可拖动 · 点击节点阅读单指拖动平移 · 使用 + / − 按钮缩放 · 点击节点阅读

当前文章引用本文
引用列表

引用本文1

  • LeetCode Programming
    AI 摘要

    本文是作者为缓解拖延、练习 Go 语言而开启的 LeetCode 刷题记录,兼作个人题解。文中先介绍 C++ 输入输出加速技巧,通过 ios::sync_with_stdio(false) 解除 C/C++ 流同步、cin.tie(nullptr) 解除 cin 与 cout 绑定来提升效率;随后汇总多道 LeetCode 题解,列出题号、题目、难度及链接,涵盖第1至32题等。

本文引用0

暂无

文章关联