从递归管理的链表类中删除ch

时间:2018-04-17 01:56:43

标签: c++ recursion linked-list

我构建了这个while循环来删除与链接列表中给定var匹配的ch。我遍历列表然后删除。我想通过递归而不是迭代来管理它。我迷失在语法上。从来没有做过递归。

在标题中......

class LinkedList...

bool del(char ch);

struct node
{
    char data;
    node * next;
    node * prev;
};
node * head, *tail;

在源代码中使用迭代

bool LinkedList::del(char var){

struct node *curr;
struct node *prev;
struct node *next;

//empty?
if (head == NULL){
    cout << "sent an empty..." << endl;
    return false;
}

if (head->data == var){
    next = head->next;
    delete head;
    head = next;
    return true;
}
curr = head->next;

while (curr != NULL){
    if (curr->data == var)
    {
        prev = curr->prev;
        next = curr->next;
        delete curr;
        prev->next = next;
        return true;
    }

    curr = curr->next;

}
return false;
}

1 个答案:

答案 0 :(得分:0)

你可以试试这个。

只检查3个案例:

  • 如果当前节点为空 - 含义列表为空或列表中不存在

  • 如果当前节点数据不是var

  • 如果当前节点数据为var

示例代码

bool LinkedList::del(struct node* curr, char var) {
   if (curr == NULL) {
      // base case: haven't found var in list
      return false;
   }

   if (curr->data != var) {
      // case 2: data != var
      // search next node
      return del(curr->next, var);
   }

   // case 3: data == var
   // found it - delete this node
   struct node* next = curr->next;
   struct node* prev = curr->prev;

   prev->next = next; // time to say goodbye to curr
   delete curr;       // 

   return true;
}

del(head, var); // pass head to start