Swap Nodes in Pairs Java solutions

Source: Internet
Author: User

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.

Subscribe to see which companies asked this question

1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {val = x;}7  * }8  */9  Public classSolution {Ten      PublicListNode Swappairs (ListNode head) { One         if(Head = =NULL|| Head.next = =NULL)returnhead; AListNode res =NewListNode (0); -ListNode pre =NewListNode (0); -Res.next =head; the         BooleanIsfirst =true;//Flag whether the first time the head is processed, then point the res to the first node.  -          while(Head! =NULL&& Head.next! =NULL){ -Pre.next =Head.next; -Head.next =Pre.next.next; +Pre.next.next =head; -             if(isfirst) { +Res.next =Pre.next; AIsfirst =false; at             } -Pre =Pre.next.next; -Head =Head.next; -         } -         returnRes.next; -     } in}

The topic seems to require not change the value of the node, so only by changing the point of the next to deal with, as long as the paper to draw a good chain of disassembly process.

Swap Nodes in Pairs Java solutions

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.