我給出了指向已排序的雙向鏈表的頭節點和要插入到列表中的整數的指針。我被告知創建一個節點並將其插入到列表中的適當位置以便維護其排序的順序。頭節點可能爲NULL。在已排序的雙向鏈表中插入
採樣輸入
NULL,數據= 2
NULL < - 2 < - > 4 < - > 6 - > NULL,數據= 5
樣本輸出
NULL < - 2 - > NULL
NULL < - 2 < - > 4 < - > 5 < - > 6 - > NULL
我試過了上面的問題。但是我的程序因爲timeout而終止。我在下面的代碼中做了什麼錯誤。假設節點類和主要功能已經存在。提前謝謝了!!
Node SortedInsert(Node head,int data) {
Node newn = new Node();
newn.data = data;
newn.prev=null;
newn.next = null;
Node ptr = head;
Node nex=head.next;
while(ptr!=null && nex!=null) {
if(ptr.data<=newn.data && nex.data>=newn.data) {
newn.next = nex;
newn.prev = ptr;
nex.prev = newn;
ptr.next = newn;
}
else {
nex=nex.next;
ptr=ptr.next;
}
}
if(ptr!=null && nex==null) {
if(ptr.data>=newn.data) {
newn.next=ptr;
ptr.prev=newn;
newn.prev=null;
head=newn;
}
else {
ptr.next=newn;
newn.prev = head;
}
}
if(head==null) {
head = newn;
}
return head;
}
在聲明中,您將變量命名爲「aux1」,但隨後稱爲「aux」。而在第二,如果從最後那裏是「nexwn」應該是「newn」。在大多數情況下你都不回頭。 – Syntac
感謝您的支持,您是對的 –
沒問題。其他一個非常乾淨和好的解決方案。 – Syntac