Leetcode:swap Nodes in Pairs

Source: Internet
Author: User

Topic:
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.

Thinking Analysis:
Insert the first element after the second element for the first time, insert the third element after the fourth one, and so on.

C + + Reference code:

/*** Definition forsingly-linked list. * struct ListNode {*intVal * ListNode*next; * ListNode (int x): Val (x),Next(NULL) {} * };*/Class Solution{public:listnode*swappairs(ListNode*head)    {if(!head | |!head->Next)returnHead ListNode*previous= nullptr; ListNode*current= head; ListNode*next= head->Next; Head = head->Next;//Record the adjusted head node while(Next)        {//Insert the current node into theNextNode behind current->Next=Next-Next;Next-Next= current;//The first time previous was nullptr.if(previous) Previous->Next=Next;//After inserting, the pointer moves the next previous = current; Current = Current->Next;//Finally, current becomes nullptr, which directlyNextAlso set to Nullptr, Exit loopif(current)Next= current->Next;Else Next= nullptr; }returnHead }};

C # Reference Code:

/** * Definition forsingly-linked list. * Public classListNode {* Public intVal * PublicListNodeNext; * PublicListNode (intX) {val = x;} *} */ Public classsolution{ PublicListNode Swappairs (ListNode head) {if(Head = =NULL|| Head.Next==NULL) return head; ListNode previous =NULL;        ListNode current = head; ListNodeNext= head.Next; Head = head.Next; while(Next!=NULL) {Current.Next=Next.Next;Next.Next= current;if(Previous! =NULL) Previous.Next=Next;            previous = current; Current = current.Next;if(Current = =NULL)Next=NULL;Else Next= Current.Next;    } return head; }}

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.