| Title: |
Swap Nodes in Pairs |
| Pass Rate: |
32.5 |
| Difficulty: |
Medium |
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.
The subject is a pointer to three pointers, a pointer to the two nodes that need to be exchanged, and a pointer to their previous node,
such as: 1-"2-" 3-"4
After the operation of the 3,4 Exchange to 2 points to 4, can not point to 3, in addition, the first time to exchange the list of links to 2, the details of operation see Code:
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - PublicListNode Swappairs (ListNode head) { - if(head==NULL|| head.next==NULL)returnhead; theListNode res=head; -ListNode first=head,second=head.next,pre=NULL; - intI=0; -ListNode tmp=NewListNode (-1); + while(second!=NULL){ -tmp.next=Second.next; +second.next=First ; Afirst.next=Tmp.next; at if(i==0) res=second; - if(pre!=NULL) pre.next=second; -Pre=First ; -first=First.next; - if(first==NULL) Break; -Second=First.next; inI=1; - to } + returnRes; - } the}
Leetcode------Swap Nodes in Pairs