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
  • 相关阅读:
    html的基本框架和常用标签
    防火墙
    Zenmap
    每日一招:熟练掌握变盘方向
    每日一招:赚钱最快的选股策略
    操盘策略:黄金做单时间
    每日一招:坚守六大方式选出优质股
    如何保卫你的牛市胜利果实?
    名家看后市:长阴破位不必慌
    每日一招:补仓需遵守的技巧
  • 原文地址:https://www.cnblogs.com/bozhou/p/6956178.html
Copyright © 2011-2022 走看看