【Leetcode24 两两交换链表中的节点】

题目描述

在这里插入图片描述

解题思路

解法一:迭代法

原链表
在这里插入图片描述
添加空头后的链表
在这里插入图片描述
第一次交换

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

python代码

# 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:
        thead = ListNode(-1)
        thead.next = head
        c = thead
        while c.next and c.next.next:
            a = c.next
            b = c.next.next
            c.next = b
            a.next = b.next
            b.next = a
            c = c.next.next
        return thead.next

解法二

将链表的值存到列表中,再两两翻转

python代码

# 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
        a = []
        tem = ListNode(-1)
        p = tem
        # 把链表的值存储到列表当中
        while head:
            a.append(head.val)
            head = head.next
        b = len(a)//2
        # 两两进行交换
        for i in range(0,b*2,2):
            a[i],a[i+1] = a[i+1],a[i]
        # 再重新创建链表
        for j in a:
            p.next = ListNode(j)
            p = p.next
        return tem.next

s = Solution()
res = s.swapPairs(head)
print(res)
发布了56 篇原创文章 · 获赞 1 · 访问量 1664

猜你喜欢

转载自blog.csdn.net/weixin_44549556/article/details/105453075