Swap Nodes in Pairs @ LeetCode

Source: Internet
Author: User

It takes time to judge the case where an odd number of nodes and an even number of nodes are required.

Package Level2; import Utility. listNode;/*** Swap Nodes in Pairs *** Given a linked list, swap every two 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 shocould use only constant space. you may not modify the values in the list, only nodes itself can be changed. **/public class S24 {public static void main (String [] args) {ListNode n1 = new ListNode (1); ListNode n2 = new ListNode (2); n1.next = n2; ListNode n3 = new ListNode (3); n2.next = n3; n1.print (); ListNode head = swapPairs (n1); head. print ();} public static ListNode swapPairs (ListNode head) {if (head = null) {return null;} // if there is only one element, if (head. next = null) {return head;} ListNode I = head; // I points to 1st ListNode j = I. next; // j points to 2nd ListNode k = j. next; // K points to 3rd head = head. next; while (j! = Null) {j. next = I; if (k! = Null & k. next! = Null) {// when there is an even number of nodes I. next = k. next;} else {// when there is an odd number of nodes I. next = k;} // update the values of I, j, and k, forward two cells I = k; if (k! = Null) {j = k. next;} else {j = null;} if (k! = Null & k. next! = Null) {k = k. next. next;} else {k = null ;}} return head ;}}

 

 

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.