Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None
""" 解法:
1.长度小于2直接返回
2.设置一个前置节点和虚拟节点,前置节点负责连接交换过后的节点
3.遍历,相邻的2个节点交换,若只剩下1个结点,不做处理
"""
class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head cur = head dummy= pre = ListNode(None) while cur and cur.next: tmp = cur.next cur.next = cur.next.next tmp.next = cur pre.next = tmp pre = pre.next.next cur = cur.next return dummy.next