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.
Give a list of 22 exchanges.
My train of thought is two pairs of two pairs to see, but divides into three kinds of situations, this pair and the following situation is: 1-2-3-4;1-2-3;1-2;
Then according to different situations write their Exchange strategy ~ The code has comments, can not read the notes understand my ideas ~
The main function is included for you to test!!!
public class Swapnodesinpairs {public static void main (String args[]) {Swapnodesinpairs DP = new Swapnodesinpairs (); ListNode head = new ListNode (1); ListNode p1 = new ListNode (2); head.next=p1; ListNode P2 = new ListNode (3);p 1.next = p2; ListNode p3 = new ListNode (4);p 2.next = p3; ListNode P4 = new ListNode (5);p 3.next = P4;prinf (head);p Rinf (Dp.swappairs (Head));} private static void Prinf (ListNode input) {while (input!=null) {System.out.print (input.val+ "); input = Input.next;} System.out.println ();} Public ListNode Swappairs (ListNode head) {if (head==null| | Head.next==null) return head; ListNode P=head; ListNode start = Head.next; while (p!=null&&p.next!=null) {ListNode nxt = P.next; If all the following four are there, 2 is connected to the 3, then remember to let the next round of P is equal to 3 (but because the algorithm skips 3, so save 3) if (p.next.next!=null&&p.next.next.next!= NULL) {P.next=nxt.next.next; ListNode tmp = nxt.next;//3 nxt.next=p early deposit; p=tmp;//let the next P equals 3, and if P.next, the next one is 4, and 3 is skipped forever. }//If there are three behind, this is the end of the pair, there is one left, then the last one does not move, the two Exchange else if (P.next.next!=null&&p.next.next.next==null) { P.next=nxt.next; nxt.next=p; P=p.next; }//On the last two, you can exchange the else if (p.next.next==null) {nxt.next=p; P.next=null; }} return start; }}
"Leetcode" Swap Nodes in Pairs in JAVA rare write-to-change. Bonus test program like always