题解 | 两两交换链表中的结点

两两交换链表中的结点

https://www.nowcoder.com/practice/1aabdaea8c7e4874bb1d3eda2c7f0042

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @return ListNode类
#
class Solution:
    def swapPairs(self , head: ListNode) -> ListNode:
        # write code here

        #相当于从最后一组互换位置,不断往前推
        #当头结点为空,或只有一个数据时,无需交换,只需返回原头结点
        if not head or not head.next:
            return head

        #新头结点为原头结点的next
        new_head = head.next

        #原头节点的next继续进行交换递归,此时位置还未换所以相当于为head.next.next
        head.next = self.swapPairs(new_head.next)

        #新头结点与原头节点换位置
        new_head.next = head
        
        #返回新头结点
        return new_head
            

        

全部评论

相关推荐

12-27 22:35
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务