Leetcode Swap Nodes in Pairs

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.

Problem Solving Ideas:

You need to use Fakehead to point to the original pointer, to prevent the chain, with two pointers, thepre always points to the pair that needs to be exchanged before a node,cur always points to the first node of the pair that needs to be exchanged.

Then just make a normal list exchange, and the pointer moves just fine.

When the list length is odd, the cur.next may be null;

Cur may be null when the list length is even.

So the two conditions as the termination condition, in the while judgment is good, and finally return to Fakehead.next.

Linked list Exchange I don't understand, I need someone to help me to tell.

Java Code:

 Public classSolution { PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.next = =NULL){            returnHead; } ListNode Fakehead=NewListNode (0); Fakehead.next=Head; ListNode Pre=Fakehead; ListNode cur=Head;  while(cur!=NULL&& Cur.next! =NULL) {Pre.next=Cur.next; Cur.next=Cur.next.next; Pre.next.next=cur; Pre=cur; Cur=Cur.next; }        returnFakehead.next; }}

Reference:

1. http://bangbingsyb.blogspot.com/2014/11/leetcode-swap-nodes-in-pairs.html

2. http://www.cnblogs.com/springfor/p/3862030.html

Leetcode 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.