<递归>
题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定1->2->3->4
, 你应该返回2->1->4->3
.
题解 - 迭代
class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ pre = ListNode(-1) pre.next = head ret = pre while head and head.next: fst = pre.next sec = head.next pre.next = sec fst.next = sec.next sec.next = fst pre = fst head = fst.next return ret.next
-
算法:
题解 - 递归