[LeetCode]题解(python):024-Swap Nodes in Pairs

时间:2022-11-27 04:44:54

题目来源:

  https://leetcode.com/problems/swap-nodes-in-pairs/


题意分析:

  给定一个链表,每两个相邻节点就行交换。比如1->2->3->4,得到2->1->4->3。要求不能改变节点的值,不能新建链表。


题目思路:

  这题是考链表的操作。首先建立一个头节点,将头节点指向第二个节点,然后再指向第一个节点,最后指向第三个节点,然后指针跳到第二个节点重复。


代码(python):

 # 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:
return None
ans = ListNode(0)
ans.next = head
tmp = ans
while tmp.next and tmp.next.next:
t = tmp.next.next
tmp.next.next = t.next
t.next = tmp.next
tmp.next = t
tmp = tmp.next.next
return ans.next

转载请注明出处:http://www.cnblogs.com/chruny/p/4872950.html