【问题标题】:Recursive way to delete the last element of a singly linked list?递归方式删除单链表的最后一个元素?
【发布时间】:2014-12-08 17:16:10
【问题描述】:
int main(){
    IntSLList list1,list2;

    list1.addToHead(1);
    list1.addToHead(2);
    list1.addToHead(3);
    list1.printAll();

    IntSLLNode *p;
    list1.assignvalues(p);

    //p....p->next...p->next->next
    //p refers to the first node of the linked list


    return 0;
}

IntSLList* IntSLList::deletelast(IntSLLNode *p)
{

    if(p==NULL || p->next ==NULL)//check this one as my base case
    {
        return NULL;
    }
    else
    {
        p->next = deletelast(p->next);
    }

}
void IntSLList::assignvalues(IntSLLNode *p)
{
    p=head;
}

有人知道我在这里做错了什么吗?它说p->next 有错误的数据类型要按原样分配......

【问题讨论】:

  • 我猜p->nextIntSLLNode*,而您正试图为其分配IntSLList* 类型的东西。但是你期望deletelast 会返回什么?

标签: c++ recursion singly-linked-list


【解决方案1】:

试试这个:

int main() {
    IntSLList list1;

    list1.addToHead(1);
    list1.addToHead(2);
    list1.addToHead(3);

    list1.deletelast(list1->head);
    list1.printAll();
}

void IntSLList::deletelast(IntSLLNode *p){
    if (p->next->next == NULL) {
        p->next = NULL;
        return;
    }
    deleteLast(p->next);
}

一些更正:

  1. 您可以通过list1->head 直接访问列表的head
  2. deleteLast 的返回类型应该只是void
  3. 基本情况应该是NULL 之前的两个节点。记住这是一个单列表,如果你停在NULL之前的一个节点,你怎么能设置前一个节点的指针不指向当前节点呢?这份清单只有一个方向,一往前就不能回头
  4. 实际上不需要递归。它与使用循环具有相同的时间复杂度。两者都是O(n)时间复杂度

【讨论】:

    【解决方案2】:

    假设您想从deletelast 退回被遗弃的物品(从列表中除名的物品)。

    试试这个:

    IntSLLNode *IntSLList::deletelast(IntSLLNode *p)
    {
        IntSLLNode *pNextNext = p->next->next;
    
        if(pNextNext == NULL)
        {
            // Next element is the last element, because
            // the element after that does not exist (pNextNext)
            p->next = NULL; // make this element the last element
            return pNextNext; // we are returning the abandoned element
                              // so caller can make memory de-allocations
                              // or whatever with the abandoned last element
        }
        else
        {
            p->next = deletelast(p->next);
        }
    
    }
    

    你可以这样调用递归函数:

    IntSLList *pList;
    // populate pList
    IntSLLNode *abandonedNode = IntSLList::deletelast(pList->head);
    // now you can do whatever you want with abandonedNode. Also, the
    // variable pList still points to the list, now reduced by one element.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-29
      • 2014-05-02
      • 2021-05-29
      • 2017-01-04
      • 2011-06-27
      • 1970-01-01
      • 2021-05-14
      • 2019-10-29
      相关资源
      最近更新 更多