[Leetcode#24] Swap Nodes in Pairs

Source: Internet
Author: User

problem:

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.

Analysis:

case Continue ... 

Wrong solution:

 Public classSolution { PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.next = =NULL)            returnHead; ListNode Dummy=NewListNode (1); ListNode Pre=dummy; Dummy.next=Head; ListNode Node1=Head; ListNode Node2=Head.next;  while(Node1! =NULL&& Node2! =NULL) {ListNode temp=Node2.next; Pre.next=Node2; Node2.next=Node1; Node1.next=temp;if(Node2.next! =NULL) {Node1=Node2.next; if(Node2.next.next! =NULL) Node2=Node2.next.next; }        }        returnDummy.next; }}

Mistakes:

Error CaseLast executed input:[The]mistake1: Mistake1: Forget to update the pointer of Node1 and Node2.temp=Node1;node1=Node2;node2=Temp;pre=Node2;mistake2:ifThere is not enough nodes (2 nodes) left, you should also update on Node2, to indicate the loop should over!if(Node2.next! =NULL&& Node2.next.next! =NULL) {Node1=Node2.next; Node2=Node2.next.next;} Else{    //inorder to exit the loop, no effect on node in the LinkedListNode2 =NULL;}

Solution:

 Public classSolution { PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.next = =NULL)            returnHead; ListNode Dummy=NewListNode (1); ListNode Pre=dummy; Dummy.next=Head; ListNode Node1=Head; ListNode Node2=Head.next;  while(Node2! =NULL) {ListNode temp=Node2.next; Pre.next=Node2; Node2.next=Node1; Node1.next=temp; Temp=Node1; Node1=Node2; Node2=temp; Pre=Node2; if(Node2.next! =NULL&& Node2.next.next! =NULL) {Node1=Node2.next; Node2=Node2.next.next; } Else{                //inorder to exit the loop, no effect on node in the LinkedListNode2 =NULL; }        }        returnDummy.next; }}

[Leetcode#24] 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.