给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定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