交换链表中的节点

给你链表的头节点 head 和一个整数 k 。

交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。

示例 1:

输入:head = 1,2,3,4,5, k = 2

输出:1,4,3,2,5

示例 2:

输入:head = 7,9,6,6,7,8,3,0,9,5, k = 5

输出:7,9,6,6,8,7,3,0,9,5

示例 3:

输入:head = 1, k = 1

输出:1

示例 4:

输入:head = 1,2, k = 1

输出:2,1

示例 5:

输入:head = 1,2,3, k = 2

输出:1,2,3

提示:

链表中节点的数目是 n

1 <= k <= n <= 105

0 <= Node.val <= 100

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        n,s,f = head,head,head
        recode = 1
        while n:
            if recode < k:
                s = s.next
            if recode >k :
                f = f.next

            n = n.next
            recode +=1
        f.val,s.val = s.val,f.val
        return head
        

怎么能有这么聪明的解法,一次遍历 找到两个节点

膜拜大佬

相关推荐
m0_5474866618 小时前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr1 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_31 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.1 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣1 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9921 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王1 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水1 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1011 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质