繁体   English   中英

没有尾指针的单链接列表上的extractLessThan操作

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM