Leetcode "Swap Nodes in Pairs" Python implementation

Source: Internet
Author: User

title :

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.

code : OJ Test via runtime:42 ms

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@param a ListNode9     #@return a ListNodeTen     defSwappairs (Self, head): One         ifHead isNoneorHead.next isNone: A             returnHead -          -Dummyhead =listnode (0) theDummyhead.next =Head -          -Pre =Dummyhead -Curr =Head +          whileCurr is  notNone andCurr.next is  notNone: -TMP =Curr.next +Curr.next =Tmp.next ATmp.next =Pre.next atPre.next =tmp -Pre =Curr -Curr =Curr.next -         returnDummyhead.next

Ideas :

Basic linked list operations.

It is important to note that while loop judgment condition: First Judge Curr not empty, then judge Curr.next not empty.

This and judgment condition has a short circuit function, and if the Curr is empty it will not make the next judgment, so it is safe

Leetcode "Swap Nodes in Pairs" Python implementation

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.