'''
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
'''
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
if head == None or head.next == None:
return head
cur = head
head = head.next
while cur and cur.next:
pNext = cur.next.next
cur.next.next = cur
if pNext:
if pNext.next:
cur.next = pNext.next
else:
cur.next = pNext
else:
cur.next = None
cur = pNext
return head
# recursion
def swapPairs2(self, head):
if not head or not head.next:
return head
first, second = head, head.next
third = second.next
head = second
second.next = first
first.next = self.swapPairs(third)
return head
python-leetcode面试题解之两两交换链表中的节点.zip
8 浏览量
2024-03-06
05:34:47
上传
评论
收藏 1014B ZIP 举报
__AtYou__
- 粉丝: 1183
- 资源: 261
最新资源
- ### 词向量的介绍、使用技巧和优缺点的文章
- 基于STM32F103CBT6单片机GC65+MP2625+CC1101 GPSTrack模块板硬件(原理图+PCB)工程文件
- ### 通道处理过程模拟概念、优缺点和使用技巧
- ### MyBatis动态SQL介绍说明、使用技巧和优缺点
- 上传下载仿163网盘无刷新文件上传 for Jsp-fileupload-jsp.rar
- VMware Workstation业界非常稳定且安全的桌面虚拟机软件-计算机上运行多个操作系统,支持Windows、DOS等
- 基于STM8L101F3P6单片机+LY2508A33P+CC1100遥控器硬件(原理图+PCB)工程文件.zip
- 上传下载WAP图铃下载系统-unimg.rar
- YTX-0.1.0-Win
- 上传下载ExtJS 2.2 开源网络硬盘系统-dogdisk.rar
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈