[Leetcode] [Python]24:swap Nodes in Pairs

Source: Internet
Author: User

#-*-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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.