-1
我正試圖解決hackerrank上的問題。要解決的問題是:排序雙向鏈表(Java空指針)的問題
「給出指向已排序的雙向鏈表的頭節點的指針和要插入列表的整數。創建一個節點並將其插入列表中的適當位置。頭節點可能爲NULL,表示列表爲空。「
他們提供的節點類定義爲
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
Node prev;
}
*/
我嘗試的解決方案是
Node SortedInsert(Node head,int data)
{
// new node to insert into linked list
Node newNode = new Node();
newNode.data = data;
if (head == null)
{
return newNode;
}
else
{
// start at beginning of list
Node cur = head;
// traverse through sorted list
while (cur != null && cur.next != null)
{
if (data < cur.next.data)
{
newNode.next = cur.next;
newNode.prev = cur;
cur.next.prev = newNode;
cur.next = newNode;
return head;
}
else
{
cur = cur.next;
}
}
return head;
}
}
我不太知道什麼是錯在這裏,但hackerrank是說我的解決方案是不正確。有什麼想法可能會出錯?
你是否運行在IDE調試代碼? _「不起作用」_對問題描述不夠。 –
我沒有嘗試在IDE調試器中運行它,但我自己卻發現了這個問題。感謝您指出我問題的模糊性,下次我會記住這一點,以便更具體。 – Surfero