#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
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.
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# 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 None == head:
return None
node = head
while node != None and node.next != None: #小心点越界就好
tmp = node.val
node.val = node.next.val
node.next.val = tmp
node = node.next.next
return head
25 leetcode - Swap Nodes in Pairs
最新推荐文章于 2025-08-17 23:50:11 发布