Q:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定1->2->3->4
2->1->4->3
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/description/
思路:
代码:
# 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:
return []
tmp = []
while head:
tmp.append(head)
head = head.next
if len(tmp) < 2:
return tmp[0]
last = (len(tmp))%2
for i in range(0,len(tmp)-last,2):
tmp[i],tmp[i+1] = tmp[i+1],tmp[i]
head_ = point = tmp.pop(0)
point.next = None
while tmp:
point.next = tmp.pop(0)
point = point.next
point.next = None
return head_