Swap Nodes in Pairs

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.


1  Public classSolution {2      PublicListNode Swappairs (listnode head)3     {4         if(Head = =NULL|| Head.next = =NULL)returnhead;5ListNode Fakehead =NewListNode (0);6Fakehead.next =head;7         8ListNode PTR0 =Fakehead;9ListNode PTR1 =Fakehead.next;Ten          One          while(ptr1!=NULL&&ptr1.next!=NULL) A         { -ListNode PTR2 =Ptr1.next; -ListNode PTR3 =Ptr1.next.next; theptr0.next=ptr2; -ptr2.next=ptr1; -ptr1.next=PTR3; -ptr0=ptr1; +ptr1=PTR3; -              +         } A          at         returnFakehead.next; -     } -}

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.