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