数据结构和算法分析算法提高之LeetCode刷题Leetcode

leetcode.24 - 两两交换链表中的节点

2019-04-20  本文已影响1人  半亩房顶

题目

swap-nodes-in-pairs
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

思路

思路还是挺简单的

代码

递归法:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        pHead=head
        pHeadNext=head.next
        pHead.next=self.swapPairs(pHeadNext.next)
        pHeadNext.next=pHead
        return pHeadNext

非递归法:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        new_h = ListNode(-1)
        new_h.next = head
        p1 = new_h
        p2 = p1.next
        
        while p2!=None and p2.next!=None:
            p1.next = p2.next
            p2.next = p1.next.next
            p1.next.next = p2
            
            p1 = p2
            p2 = p2.next
        
        return new_h.next

以上

欢迎大家关注我的公众号


半亩房顶
上一篇 下一篇

猜你喜欢

热点阅读