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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM