zl程序教程

您现在的位置是:首页 >  其他

当前栏目

【LeetCode】24. 两两交换链表中的节点

2023-09-14 09:13:25 时间

1. 题目

在这里插入图片描述

2. 分析

用了两种思路解决这个问题,这种题如果出现在面试题中,那有点儿悬了。实在是不熟练。

2.1 方法一

step1. 将链表分割成两串链表,其中奇数位的为一串,偶数下标位为一串。
step2. 再将链表交错合并

2.2 方法二

直接暴力倒转,这种方法更简单。

3. 代码

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if head is None:
            return 
        if head.next is None:
            return head
        start = head.next
        pre = None
        while(head):
            # 如果满足条件说明可以交换
            if head.next is not None:
                tmp_2 = head.next.next # 下次的head
                tmp_1 = head.next               
                tmp_1.next = head
                if pre is not None:
                    pre.next = tmp_1
                
                pre = head
                head.next = tmp_2
                head = tmp_2
            else:
                if pre is not None:
                    pre.next = head
                else: # 说明只有一个节点
                    pre = head
                head = head.next
            
        return start  # 返回头节点