美文网首页
leetcode24. 两两交换链表中的节点

leetcode24. 两两交换链表中的节点

作者: 冰源 | 来源:发表于2018-09-26 11:05 被阅读13次
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:

你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        end=ListNode(None)
        if head!=None and head.next!=None:
            idx = head
            head=head.next.next

            start=idx.next
            start.next=idx
            idx.next=head
            end.next=start
            end=idx
            res=start
        else:return head
        while head!=None and head.next!=None:
            idx = head
            head=head.next.next

            start=idx.next
            start.next=idx
            idx.next=head
            end.next=start
            end=idx
        return res

相关文章

网友评论

      本文标题:leetcode24. 两两交换链表中的节点

      本文链接:https://www.haomeiwen.com/subject/hfjdoftx.html