Twenty-two switching node in the list -24

Given a list pairwise exchange with adjacent nodes, and return the list to the exchange.

You can not just simply change the internal node values, but need to be the actual node exchange.

 

Example:

Given 1-> 2-> 3-> 4, you should return 2-> 1-> 4-> 3.

 1 public class T24 {
 2 
 3     public ListNode swapPairs(ListNode head) {
 4         if (head == null) {
 5             return head;
 6         }
 7         ListNode dummy = new ListNode(-1);
 8         dummy.next = head;
 9         ListNode pre = dummy;
10 
11 
12         while (head != null && head.next != null) {
13 
14             ListNode p1 = head;
15             ListNode p2 = head.next;
16 
17             //exchange
18             pre.next = p2;
19             p1.next = p2.next;
20             p2.next = p1;
21 
22             //continue
23             pre = p1;
24             head = pre.next;
25 
26         }
27         return dummy.next;
28 
29     }
30 }

 

Guess you like

Origin www.cnblogs.com/zzytxl/p/12507999.html