Swap Nodes in Pairs, swap elements for pairs

Source: Internet
Author: User

Problem Description: Give a sequence, swap each adjacent two elements, and return the head node. For example: 1-2-3-4 return sequence 2-1-4-3

Algorithm idea: In addition to the first set of elements, each other to exchange a pair of elements, to change four pointers. So, define four pointers. Only two of these pointers are not wanted off, others depend on these two pointers.

 Public StaticListNode Swappairs (ListNode head) {ListNode Pprepre=NULL;//former elements of a node pairListNode Ppre =NULL;//The previous element of a node pair, dependent on pListNode p = head;//The first element of a pair of nodes to moveListNode Pnext =NULL;//the second element of a pair of nodes, dependent on p         while(P! =NULL&& P.next! =NULL) {Ppre=p; P=P.next; Pnext=P.next; if(Ppre = =head) {Head=p; }            if(Pprepre! =NULL) {Pprepre.next=p; } P.next=Ppre; Ppre.next=Pnext; Pprepre= Ppre;//all other elements depend on p, but Pprepre does not depend on p, so each move Pprepre and Pp =Pnext; }        returnHead; }

Swap Nodes in Pairs, paired pairs of elements

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.