题目链接
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.csdn.net/coder_orz/article/details/51532184