24. 两两交换链表中的节点

<递归>

题目


 

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:

给定 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

 

 

  • 算法:

 

 

题解 - 递归


 

 

 

posted @ 2019-09-19 16:55  remly  阅读(195)  评论(0编辑  收藏  举报