当前位置: 代码迷 >> 综合 >> LeetCode 24.两两交换链表中的节点
  详细解决方案

LeetCode 24.两两交换链表中的节点

热度:8   发布时间:2023-10-21 02:41:18.0

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def swapPairs(self, head):""":type head: ListNode:rtype: ListNode"""if not head or not head.next:return headp=headq=head.next        newhead=qwhile p and q:temp=q.nextif temp:if temp.next:p.next=temp.nextelse:#链表个数为奇数,temp指向最后一个时p.next=tempelse:#temp为链表结尾p.next=Noneq.next=pp=tempif p:q=p.nextreturn newhead