我一直试图通过交换节点来解决单链表中的选择排序问题。 面对错误:运行时出现java.lang.NullPointerException。关于我哪里出错的任何输入。
class Solution {
public ListNode sortList(ListNode head) {
// if there is only a single node
if (head.next == null)
return head;
// 'min' - pointer to store the node having
// minimum data value
ListNode min = head;
// 'beforeMin' - pointer to store node previous
// to 'min' node
ListNode beforeMin = null;
ListNode ptr;
// traverse the list till the last node
for (ptr = head; ptr.next != null; ptr = ptr.next) {
// if true, then update 'min' and 'beforeMin'
if (ptr.next.val < min.val) {
min = ptr.next;
beforeMin = ptr;
}
}
// if 'min' and 'head' are not same,
// swap the head node with the 'min' node
if (min != head)
swapNodes(head, head, min, beforeMin);
// recursively sort the remaining list
head.next = sortList(head.next);
return head;
}
public void swapNodes(ListNode head, ListNode currX,ListNode currY, ListNode prevY){
// make 'currY' as new head
head = currY;
// adjust links
prevY.next = currX;
// Swap next pointers
ListNode temp = currY.next;
currY.next = currX.next;
currX.next = temp;
}}
答案 0 :(得分:0)
尝试在函数顶部添加:
if(head == null) 回头;