赞
踩
题目:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路一:递归
解答一:递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
newHead = head.next
head.next = self.swapPairs(newHead.next)
newHead.next = head
return newHead
思路二:非递归
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: ListNode) -> ListNode: pre=ListNode() pre.next=head cur=pre while cur.next and cur.next.next: #tmp1和tmp2用来记录临时节点 tmp1=cur.next tmp2=cur.next.next.next cur.next=tmp1.next cur.next.next=tmp1 tmp1.next=tmp2 cur=tmp1 return pre.next
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。