24. Swap Nodes in Pairs

题目

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

思路

首先判断是否可以取到2个节点,如果可以,对这两个节点的next进行交换,同时存储交换后的第二个节点为pre,下一轮取两个节点,当交换完后,把第一个节点赋给pre.next,保证上一步和下一步链接好

Python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 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 or head.next==None:
return head
h=head.next
pre=None
while(head!=None and head.next!=None):
p1=head
p2=head.next
temp=p1
p1.next=p2.next
p2.next=temp
head=p1.next
if pre!=None:pre.next=p2
pre=p1
return h
如果觉得有帮助,给我打赏吧!