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

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time: 2019/3/13
# @Author: xfLi
# The file...

# 思路主要是,设置两个指针,一个在前一个在后,进行交互,此外还需要一个额外的指针做辅助。

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def swapPairs(head):
    if not head: return None
    root = ListNode(0)
    root.next = head

    slow = head  # 较慢的指针,在后面
    fast = head.next  # 较快的指针,在前面
    pre = root  # 设置一个辅助指针

    while fast:
        slow.next = fast.next
        fast.next = slow
        pre.next = fast
        pre = slow
        if not slow.next:
            break
        slow = slow.next
        fast = slow.next
    return root.next

猜你喜欢

转载自blog.csdn.net/qq_30159015/article/details/88537314