leetcode 24. 两两交换链表中的节点

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 1 class ListNode {
 2     int val;
 3     ListNode next;
 4     ListNode(int x) { val = x; }
 5 }
 6 
 7 public class _24 {
 8     public ListNode swapPairs(ListNode head) {
 9         if (head == null || head.next == null) return head;
10 
11         ListNode t=head;
12         ListNode p = t.next;
13         ListNode q = p.next;
14         // 交换第一个和第二个
15         t.next = p.next;
16         p.next = t;
17         head = p;
18 
19         // 交换中间的
20         p = t.next;
21         if (t.next == null || t.next.next == null)
22             return head;
23         q = p.next;
24         while (true){
25             p.next = q.next;
26             q.next = p;
27             t.next = q;
28 
29             t = p;
30             if (t.next == null || t.next.next == null)
31                 break;
32             p = t.next;
33             q = t.next.next;
34         }
35         return head;
36     }
37 
38     public ListNode create(int n){
39         ListNode head = new ListNode(-1);
40         ListNode t = head;
41         for (int i = 0; i < n; i++){
42             ListNode p = new ListNode(i);
43             t.next = p;
44             p.next = null;
45             t = p;
46         }
47 
48         return head;
49     }
50     public void print(ListNode h){
51         while(h!=null){
52             System.out.print(h.val+", ");
53             h = h.next;
54         }
55     }
56 
57     public static void main(String[] args) {
58         _24 obj = new _24();
59         ListNode head = obj.create(5);
60         head = head.next;
61         ListNode h = obj.swapPairs(head);
62         obj.print(h);
63     }
64 }

 

posted @ 2019-09-15 11:12  赤云封天  阅读(168)  评论(0编辑  收藏  举报