当前位置:网站首页>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. 两数相除
边栏推荐
- 从产品角度看 L2 应用:为什么说这是一个游乐场?
- LeetCode_152_乘积最大子数组
- Stroke Practice - 62 Valid Sudokus
- 第二十二章 源代码文件 REST API 参考(四)
- Alibaba最新神作!耗时182天肝出来1015页分布式全栈手册太香了
- POJ 1026 Cipher (置换群)
- Redis设计与实现
- mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded
- WeChat applet, global variables change in one place and the state in other places also changes.
- 实现内网穿透的最佳解决方案(无实名认证,完全免费)
猜你喜欢

ViT结构详解(附pytorch代码)

In August the DB list latest scores - database Engines

std::move()

3款不同类型的自媒体免费工具,有效提高创作、运营效率

ISO9001在讲什么?过程方法和风险思维

【勇敢饭饭,不怕刷题之链表】链表倒数节点问题

VSCode remote connection server error: Could not establish connection to "xxxxxx" possible error reasons and solutions

如何使用工程仪器设备在线监测管理系统

SQL优化最强总结 (建议收藏~)

常量及数据类型你还记得多少?
随机推荐
The brave rice rice, does not fear the brush list of 】 list has a ring
第2章-矩阵及其运算-矩阵运算(2)
老板加薪!看我做的WPF Loading!!!
基于UiAutomator2+PageObject模式开展APP自动化测试实战
【勇敢饭饭,不怕刷题之链表】链表反转的几种情况
Licking Exercise - 60 Maximum key-value sum of binary search subtrees
The impact of development mode on testing
使用.NET简单实现一个Redis的高性能克隆版(六)
LeetCode_443_压缩字符串
HCIP ---- VLAN
从产品角度看 L2 应用:为什么说这是一个游乐场?
Break through the dimensional barriers and let the dolls around you move on the screen!
接口定义与实现
力扣练习——62 有效的数独
OSSCore 开源解决方案介绍
Licking Exercise - 63 Find all anagrams in a string
Buckle exercise - rectangular area does not exceed the maximum value of K and (hard)
如何使用工程仪器设备在线监测管理系统
mysql出现:ERROR 1524 (HY000): Plugin ‘123‘ is not loaded
HDU 1520 Anniversary party (tree dp)