给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
链接:https://leetcode.com/problems/swap-nodes-in-pairs/
解题思路:
创建一个头结点,使得原链表头结点的处理方式和其他结点相同。
我的代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
h = ListNode(0)
h.next = head
head = h
while h.next and h.next.next:
p = h.next
h.next = p.next
p.next = p.next.next
h.next.next = p
h = p
return head.next
Time: O(N)
Space: O(1)