首页 > 代码库 > Leetcode: Swap Nodes in Pairs

Leetcode: Swap Nodes in Pairs

坑爹地多次过,全都是写程序时不注意的小问题,书写习惯还需要进一步改善。遇到的bug有:忘记return语句;定义ListNode runner = head.next,却将判断head==null的情况放在这句之后; 忘记了新的head将不会是原来的那个head,而是head.next;

所以以后遇到runner.next.next的情况要先确保runner.next != null; 遇到runner.next的情况要先确保runner != null

 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  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode swapPairs(ListNode head) {
14         if (head == null) return null;
15         ListNode current = head;
16         ListNode runner = head.next;
17         ListNode prev = new ListNode(0);
18         prev.next = current;
19         if (current != null && runner == null) return current;
20         ListNode newhead = head.next; //save the new head;
21         while (runner.next != null){
22             if(runner.next.next != null){
23                 current.next = runner.next;
24                 runner.next = current;
25                 prev.next = runner;
26                 current = current.next;
27                 runner = runner.next.next.next;
28                 prev = prev.next.next;
29             }
30             else break;
31         }
32         current.next = runner.next;
33         runner.next = current;
34         prev.next = runner;
35         return newhead;
36     }
37 }

 别人一个很好的解法:

 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  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode swapPairs(ListNode head) {
14         // Start typing your Java solution below
15         // DO NOT write main() function
16         ListNode dummy = new ListNode(0);
17         dummy.next = head;
18         ListNode curr = dummy;
19         ListNode node1 = null;
20         ListNode node2 = null;
21         
22         while(curr.next!=null && curr.next.next!=null){
23             node1 = curr.next;            
24             node2 = node1.next;
25             ListNode next =node2.next;            
26             curr.next = node2;
27             node2.next = node1;
28             node1.next = next;            
29             curr=node1;
30         }
31         return dummy.next;
32     }
33 }