#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
24:swap Nodes in Pairs
https://oj.leetcode.com/problems/swap-nodes-in-pairs/
Given a linked list, swap every, 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. Modify the values in the list, only nodes itself can be changed.
===comments by dabay===
The operation of the linked list. It's mostly about assigning next, and if this next point node is useful, record it first.
Here, use previous to point to the front node of a pair of node to be swapped. The node to be swapped is node1 and node2 in turn.
‘‘‘
# Definition for singly-linked list.
Class ListNode:
def __init__ (self, x):
Self.val = X
Self.next = None
Class Solution:
# @param a ListNode
# @return A ListNode
def swappairs (self, head):
previous = New_head = ListNode (0)
New_head.next = Head
While previous and Previous.next and Previous.next.next:
Node1 = Previous.next
Node2 = Node1.next
Node1.next = Node2.next
Previous.next = Node2
Node2.next = Node1
Previous = Node1
Return New_head.next
def print_listnode (node):
While node:
Print "%s->"% node.val,
node = Node.next
Print "END"
def main ():
Sol = solution ()
node = root = ListNode (1)
For I in Xrange (2, 5):
Node.next = ListNode (i)
node = Node.next
Print_listnode (Root)
Print_listnode (Sol.swappairs (Root))
if __name__ = = ' __main__ ':
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]24:swap Nodes in Pairs