[英]Bool function always true & Tail Node Removal in Singly-Linked List creates infinite loop
[英]extractLessThan operation on a singly-linked list with no tail pointer
在最近的測試中,這是一個編程問題。 我最初沒有正確回答,但是我已經編輯了原始解決方案並將新更新的答案發布在問題下方。 我想知道我的解決方案是否朝着正確的方向發展,還是我的邏輯沒有道理?
在沒有尾指針的單鏈接列表上實現extractLessThan操作。 您的代碼應該不需要刪除內存。 您的代碼不得調用其他LinkedList函數。 提取的節點的順序無關緊要。
struct LinkNode {
Data * data; // note that you can compare by calling data->compareTo(other)
LinkNode * next;
};
class LinkedList {
LinkNode * head;
/**
* Returns a new LinkedList that contains all of the LinkNodes from this
* LinkedList that has node->data->compareTo(value).
* LinkedList * x = ... // x contains [5, 8, 1, 3]
* Data * value = new IntegerData(4);
* LinkedList * y = x->extractLessThan(value);
* // x now contains [5, 8] and y now contains [3, 1]
*/
// You have access to head and to this
LinkedList * extractLessThan(Data * value) {
LinkedList * newList = new LinkedList();
LinkNode * current = head;
LinkNode * previous = NULL;
*-----------------------MY SOLUTION---------------------------------->
while(current){
if(current->data->compareTo(value) < 0){
newList->head = current;
current = current->next;
return extractLessThan(value);
else {return;}
}
不,甚至沒有接近。 您不能從另一個列表中取出節點並將其插入到您的列表中,而以某種方式認為您已經完成了-您正在破壞原始列表。 您只能復制值,但是每個節點必須是新節點並屬於新列表。
另外我不確定為什么要返回extractLessThan(value)
。 即使假設這是函數,而您的狗只吃了定義,而忽略了以后您什么也不返回的事實,則無需在此處遞歸。 您已經前進到下一個節點: current=current->next;
。
LinkedList *newList = new LinkedList();
LinkNode *newListHead;
LinkNode *prev;
LinkNode *current = head;
LinkNode *next;
if (head->data->compareTo(value) < 0) {
head = head->next;
newList->head = current;
newListHead = current;
}
prev = current;
current = current->next;
while(current != NULL){
if(current->data->compareTo(value) < 0){
next = current->next;
if (newList->head == NULL) {
newList->head = current;
newListHead = current;
} else {
newListHead->next = current;
newListHead = newListhead->next;
}
current = next;
prev->next = next;
} else {
prev = current;
current = current->next;
}
}
return newList;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.