题目链接
https://leetcode.com/problems/swap-nodes-in-pairs/
题目原文
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.
题目翻译
给定一个单链表,交换相邻的节点,并返回链表头。比如,给定1->2->3->4,你应该返回 2->1->4->3。
注意:你的算法应该是O(1)的空间复杂度,不能修改链表节点的值(val),只能修改节点。
思路方法
思路一
既然每次交换相邻节点,那么就以两个节点为一个单位做处理,循环每次交换两个相邻节点即可。
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
pre = new_head = ListNode(0)
while head and head.next:
tmp = head.next
head.next = tmp.next
tmp.next = head
pre.next = tmp
pre = head
head = head.next
return new_head.next
说明
上面的思路,可以换个角度考虑:现在是用现在的节点构造一个新的链表,每次向新链表添加两个节点,这两个节点是原链表的相邻节点的逆序。
思路二
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
new_head = head.next
head.next = self.swapPairs(head.next.next)
new_head.next = head
return new_head
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51532184

本博客介绍了LeetCode中的一道题目——交换链表中的相邻节点,要求在O(1)空间复杂度下完成。文章提供了两种Python解题思路,思路一是以两个节点为单位进行交换,思路二是通过构造新链表来实现相邻节点的逆序插入。文章最后邀请读者指出错误并标明转载来源。
578

被折叠的 条评论
为什么被折叠?



