leetcode hot100 两两交换链表之中的节点
24. 两两交换链表中的节点
已解答
中等
相关标签
相关企业
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
start = None
prev =None
p=head
count=1
while p:
if count%2==1 and p.next:
if count == 1:
start = p.next
tmp = p.next
p.next = tmp.next
tmp.next = p
if prev:
prev.next = tmp
count+=1
elif count%2==1:
if count==1:
return head
else:
return start
else:
count+=1
prev=p
p=p.next
return start
简单,认真写就行