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

leetcode笔记--Swap Nodes in Pairs

2016-02-19 15:59 579 查看
题目:难度(Medium)

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.

Tags:Linked List

Similar Problems:(H) Reverse Nodes in k-Group

分析:关键是用指针记录下几个关键位置,若q指向要交换的第一个节点,则要交换的节点是q与q.next,那么需要记录的还有q的前驱结点p,和q.next的后继节点r

代码实现:

# 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 is None or head.next is None:
return head
#如果head至少有2个节点,就需要有交换操作
#先交换前2个
p = head
head = head.next
p.next = head.next
head.next = p

#交换第3个节点开始的剩余链表部分
while p.next is not None:
q = p.next
if q.next is not None:
r = q.next.next

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