赞
踩
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
给定 1->2->3->4, 你应该返回 2->1->4->3.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ #先判断链表最后两位是否都存在 if head == None or head.next == None: return head #1 和#3实现了前面两个节点互换.next等于head偶数节点 next = head.next #2 递归1,3,5,7... head.next = self.swapPairs(next.next) #3 next.next等于head奇数节点 next.next = head #每一次递归都是next存储了交换一次的head链表 return next
参考:https://blog.csdn.net/rosefun96/article/details/105407252
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。