您的位置:首页 > Web前端 > Node.js

Swap Nodes in Pairs

2015-06-11 15:51 477 查看
题目:

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.
解题思路:
这题主要涉及到链表的基本操作。加一个头结点,操作起来会很方便。另外配了一个示意图

# Definition for singly-linked list.

# class ListNode:

# def __init__(self, x):

# self.val = x

# self.next = None

class Solution:

# @param {ListNode} head

# @return {ListNode}

def swapPairs(self, head):

sentry_node = ListNode(0)

sentry_node.next = head

pre,suc = sentry_node,head

while (suc and suc.next):

pre.next = suc.next

suc.next = pre.next.next

pre.next.next = suc

pre, suc = suc,suc.next

return sentry_node.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: