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

时间:2015-07-27 03:43:26

标签: c++

在最近的测试中,这是一个被问到的编程问题。我原本没有正确回答,但我编辑了原始解决方案,并在问题下方发布了新的更新答案。我想知道我的解决方案是否朝着正确的方向前进,还是我的逻辑没有意义?

在没有尾指针的单链表上实现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;}
    }

2 个答案:

答案 0 :(得分:0)

不,甚至没有关闭。你不能从另一个列表中取出节点并将它们插入你的节点,并以某种方式认为你已经完成了 - 你正在破坏原始列表。您只能复制值,但每个节点必须是新的并且属于新列表。

此外,我不确定你为什么要归还extractLessThan(value)。即使假设这是函数,你的狗只是吃了定义,而忽略了你以后什么都不返回的事实,这里不需要递归。您已进入下一个节点:current=current->next;

答案 1 :(得分:0)

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;