• 24. Swap Nodes in Pairs


    Given a linked list, swap every two adjacent nodes and return its head.

    Example:

    Given 1->2->3->4, you should return the list as 2->1->4->3.

    Note:

    • Your algorithm should use only constant extra space.
    • You may not modify the values in the list's nodes, only nodes itself may be changed.
    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    """ 解法:
    1.长度小于2直接返回
    2.设置一个前置节点和虚拟节点,前置节点负责连接交换过后的节点
    3.遍历,相邻的2个节点交换,若只剩下1个结点,不做处理
    """
    class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head cur = head dummy= pre = ListNode(None) while cur and cur.next: tmp = cur.next cur.next = cur.next.next tmp.next = cur pre.next = tmp pre = pre.next.next cur = cur.next return dummy.next
  • 相关阅读:
    洛谷P3157 [CQOI2011]动态逆序对
    CDQ分治
    快速数论变换(NTT)
    洛谷P3338 [ZJOI2014]力
    洛谷 P1919 A*B Problem升级版
    0-1分数规划
    洛谷P4593 [TJOI2018]教科书般的亵渎
    拉格朗日插值
    20180912-3 词频统计
    20190912-1 每周例行报告
  • 原文地址:https://www.cnblogs.com/boluo007/p/10338352.html
Copyright © 2020-2023  润新知