数据结构算法操作试题(C++/Python)——两两交换链表中的节点

时间:2022-07-24
本文章向大家介绍数据结构算法操作试题(C++/Python)——两两交换链表中的节点,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

数据结构算法操作试题(C++/Python):数据结构算法操作试题(C++/Python)——目录


1. 题目

leetcode 链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/submissions/

2. 解答

python:24ms,10.7MB, 99.03%

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        tmp_head = pre_head = ListNode(0)
        pre_head.next = head
        while tmp_head.next and tmp_head.next.next:
            next2_p = tmp_head.next.next.next
            tmp_head.next.next.next =  tmp_head.next
            tmp_head.next = tmp_head.next.next
            tmp_head.next.next.next = next2_p
            tmp_head = tmp_head.next.next
        return pre_head.next

其他方法看 leetcode 链接 评论区~