循环双链表C ++

时间:2016-04-23 02:05:00

标签: c++ linked-list

removeNode()函数实现了一个具有sentinel节点的循环双向链表。我想要做的是在函数旁边的伪代码中定义。我只是很难理解如何这样做。

#include "CDLList.h"

#include <iostream>

using namespace std;

ListNode *createList()
{
    ListNode *sentinel = new ListNode();
    sentinel->last = sentinel;
    sentinel->next = sentinel;

    return sentinel;
}

void destroyList(ListNode *&sentinel)
{
    // Delete any item nodes
    clearList(sentinel);

    // Delete the sentinel node
    delete sentinel;
    sentinel = nullptr;
}

bool isEmpty(ListNode *sentinel)
{
    return (sentinel == sentinel->next);
}

ListNode *findNode(ListNode *sentinel, string value)
{
    ListNode *pCurrNode = sentinel->next;
    while (pCurrNode != sentinel)
    {
        // Check if we found the node
        if (pCurrNode->item == value)
        {
            return pCurrNode;
        }

        // Move to next node
        pCurrNode = pCurrNode->next;
    }

    return nullptr;
}

void addItem(ListNode *sentinel, string value)
{
    ListNode *newNode = new ListNode;
    newNode->item = value;
    newNode->last = sentinel->last;
    newNode->next = sentinel;

    sentinel->last->next = newNode;
    sentinel->last = newNode;
}

void removeNode(ListNode *node) // Implement this function!
{
    // Unlink node

    // Delete node
}

在这两个函数中调用removeNode()函数

void removeItem(ListNode *sentinel, string value)
{
    ListNode *node = findNode(sentinel, value);

    // If the item was not found, there's nothing to do (remove)
    if (node == nullptr)
    {
        return;
    }

    removeNode(node);
}
void clearList(ListNode *sentinel)
{
    while (!isEmpty(sentinel))
    {
        removeNode(sentinel->next);
    }
}

1 个答案:

答案 0 :(得分:2)

这是函数实现:

void removeNode(ListNode *node)
{
    if(!isEmpty(node))
    {
        ListNode* nodeLast = node->last;
        ListNode* nodeNext = node->next;

        // Unlink node
        nodeLast->next = nodeNext;
        nodeNext->last = nodeLast;
    }

    // Delete node
    delete node;
}