当前位置:网站首页>LeetCode50天刷题计划(Day 16—— 两两交换链表中的节点(9.10-10.30)
LeetCode50天刷题计划(Day 16—— 两两交换链表中的节点(9.10-10.30)
2022-08-10 11:01:00 【国际知名观众】
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
简单的链表题,但是不能小看,要细心的,不然就是无穷的debugQAQ
最近感觉题目越来越简单了,正在考虑要不要一天刷两道题捏~
一、题目
两两交换链表中的节点
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
二、思路
给链表加工头结,点然后画个草图自己转一下就行,没啥技术含量
过程中碰到的问题是
`Python3:AttributeError: ‘NoneType‘ object has no attribute ‘next‘`
报错的语句是
while(q.next):
因为填入测试的样例中p首次进入循环并不是为空的,所以就没有注意,但是好像还是应该判断一下p是否为None才能过,不然一直报错
改为如下就可以了:
while(q and q.next):
三、代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
#先造个头结点
head1=ListNode(val=0,next=head)
#双指针pq循环
p=head1 #指向头结点
q=head #指向首节点
while(q and q.next):
p.next=q.next #q的前一个元素指向q的后一个元素
temp=q.next.next #保存q的后一个元素的后一个元素
q.next.next=q #q的后一个元素指向q
q.next=temp #q指向后一个元素的后一个元素(交换前序列中)
p=p.next.next #移动指针
q=q.next
#返回
return head1.next
附:
https://leetcode.cn/problems/divide-two-integers/solution/wei-yun-suan-shi-chu-by-fyzj-rntc/
29. 两数相除
边栏推荐
- Buckle exercise - rectangular area does not exceed the maximum value of K and (hard)
- 【电商运营】你真的了解社交媒体营销(SMM)吗?
- POJ 2891 Strange Way to Express Integers (Extended Euclidean)
- [Brave food, not afraid to write the linked list] The problem of the penultimate node of the linked list
- Introduction to Software Architecture
- 即时零售业态下如何实现自动做账?
- 关于“码农”的一点自嘲解构
- 老板加薪!看我做的WPF Loading!!!
- 【小程序 | 启航篇】一文打通任督二脉
- POJ 3101 Astronomy (数学)
猜你喜欢
std::move()
【勇敢饭饭,不怕刷题之链表】链表中有环的问题
微信小程序提交审核历史版本记录从哪里查看
HCIP ---- VLAN
ISO9001在讲什么?过程方法和风险思维
Emulate stm32 directly with proteus - the programmer can be completely discarded
关于振弦采集模块及采集仪振弦频率值准确率的问题
模块九 - 设计电商秒杀系统
2022年裁员潮,失业程序员何去何从?
VSCode remote connection server error: Could not establish connection to "xxxxxx" possible error reasons and solutions
随机推荐
CodeChef STMRRG String Merging (dp)
【勇敢饭饭,不怕刷题之链表】链表中有环的问题
【Untitled】
blocking non-blocking poll mechanism asynchronous
越折腾越好用的 3 款开源 APP
2023版揽胜运动曝光,安全、舒适一个不落
[E-commerce operation] Do you really understand social media marketing (SMM)?
POJ 3101 Astronomy (Mathematics)
Stroke Practice - 62 Valid Sudokus
POJ 2891 Strange Way to Express Integers (扩展欧几里得)
基于UiAutomator2+PageObject模式开展APP自动化测试实战
Hangdian Multi-School-Loop-(uncertainty greedy + line segment tree)
leetcode 823. Binary Trees With Factors(因子二叉树)
L2 applications from a product perspective: why is it a playground?
Redis设计与实现
Short video software development - how to break the platform homogenization
从脚本到剪辑,影像大师亲授的后期制作秘籍
三个绘图工具类详解Paint(画笔)Canvas(画布)Path(路径)
快手“弃”有赞与微盟“结亲”,电商SaaS行业竞争格局将变?
力扣练习——56 寻找右区间