Leetcode #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.

 

1. 使用dummy node保存表头

2. cur -> head -> head.next -> p

 1 class Solution(object):
 2     def swapPairs(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: ListNode
 6         """
 7         dummy = cur = ListNode(0)
 8         dummy.next = head
 9 
10         while head != None and head.next != None:
11             p = head.next.next
12             cur.next = head.next
13             cur.next.next = head
14             head.next = p
15             cur = head
16             head = p
17 
18         return dummy.next

 

posted @ 2016-11-27 09:24  lettuan  阅读(145)  评论(0编辑  收藏  举报