C ++链接列表Remove和RemoveBack函数

时间:2017-08-25 11:59:09

标签: c++ linked-list

我想知道如何使用remove(int num)和removeback(int num)创建链表?使用前缀中提供的相同格式?

#include "ll.h"

LL::LL()
{
head = NULL;
}

void LL::prepend(int num)
{
node* newNode = new node;
newNode->val = val;
newNode->next = NULL;

if (head == NULL)
{
    head = newNode;
}
else
{
    newNode->next = head;
    head = newNode;
    newNode = NULL;
}

}

void LL::remove(int num)
{

}

void LL:removeBack (int num)
{


}

我认为remove和removeBack会是同一个函数吗?正确?另外我如何传递该值

2 个答案:

答案 0 :(得分:0)

我假设remove(int num)删除了与num具有相同值的第一个节点。我将把removeBack作为练习留给你:)。

void LL:remove(int num) {
    if (!head) {
        return;
    }
    else if (head->val == num) {
        node* temp = head;
        head = head->next;
        delete temp;
        return;
    }

    node* second = head;
    node* first = head->next;

    // Iterate until we find the target, or reach the end
    while (first && first->val != num) {
        second = first;
        first = first->next;
    }

    // At this point, first points to either nullptr or the target
    if (first) {
        second->next = first->next;
        delete first;
    }
}

答案 1 :(得分:0)

如何搜索节点然后删除具有该值的节点?

void LL:remove (int num){
ListNode *nodePtr, *previousNode;
if (!head) {
    return;
}
else if (head->value == num)
{
   nodePtr = head->next;
   delete head;
   head = nodePtr;
 }
 else
 {
 nodePtr=head;
     while (nodePtr != NULL && nodePtr->value !=num){
     previousNode = nodePtr;
     nodePtr = nodePtr->next;
     }
 previousNode->next = nodePtr->next;
 delete nodePtr;
 }

}