zoukankan      html  css  js  c++  java
  • LintCode Python 简单级题目 451.两两交换链表中的节点

    题目描述:

    给一个链表,两两交换其中的节点,然后返回交换后的链表。

    样例

    给出 1->2->3->4, 你应该返回的链表是 2->1->4->3

    挑战 

    你的算法只能使用常数的额外空间,并且不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    题目分析:

    你的算法只能使用常数的额外空间,即不能新建链表;

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

    创建三个指针:

      head指向开始交换的节点的上一个节点

      n1指向需要交换的第一个节点,即head.next

      n2指向需要交换的第二个节点,即head.next.next

    循环链表,通过head不断交换n1/n2位置即可。

    源码:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        # @param head, a ListNode
        # @return a ListNode
        def swapPairs(self, head):
            # Write your code here
            new = ListNode(0)
            new.next = head
            head = new
            
            while head.next is not None and head.next.next is not None:
                n1 = head.next
                n2 = head.next.next
                # 交换n1、n2
                head.next = n2
                n1.next = n2.next
                n2.next = n1
                # 交换后的链表,n1在n2后面,将head指向n1
                head = n1
            
            return new.next
            
        # 不创建链表头是否可行?lintcode报超时。
        def _swapPairs(self, head):
            # Write your code here
            if head is None or head.next is None: 
                return head
                
            new = head
            n1 = head
            n2 = head.next
            while n1.next is not None and n2.next is not None:
                n1.next = n2.next
                n2.next = n1
                n1 = n1.next
            return new
  • 相关阅读:
    LeetCode:25 K个一组翻转链表
    LeetCode:3 无重复字符的最长子串(双指针)
    Java——参数问题与final实例域
    Java——对象的构造
    配置远程服务器 安装iis 远程服务器网络无法连接
    未能找到元数据文件
    ef 设计model 标签
    visualsvn for vs2017 初始化错误
    resharper 2018.2.3破解
    C# winform 自定义函数中找不到Form中的控件和定义的全局变量
  • 原文地址:https://www.cnblogs.com/bozhou/p/6956178.html
Copyright © 2011-2022 走看看