双链表函数c ++(作业)

时间:2018-06-05 11:06:50

标签: c++

我的教授给了我们以下代码进行修改,这些代码以链接列表开头,并告诉我们制作一个双向链表。 我的displayLast()函数只显示与display()相同的顺序,而addEnd()函数没有错误,它在尝试显示值时会发生错误。 我想得到< displayLast()'反过来显示,然后希望我可以自己找出最后的添加。

/*******************************
*  Week 2 lesson:              *
*   a simple LinkedList class  *
*******************************/

#include <iostream>
#include "LinkedList.h"

using namespace std;

/*
* Initializes the list to empty creating a dummy header node.
*/
LinkedList::LinkedList()
{
    first = new Node;
    first->next = NULL;


}

/*
* Destructor. Deallocates all the nodes of the linked list,
* including the header node.
*/
LinkedList::~LinkedList()
{
    Node *temp;

    while (first != NULL)
    {
        temp = first;
        first = first->next;
        delete temp;
    }
}

/*
* Determines whether the list is empty.
*
* Returns true if the list is empty, false otherwise.
*/
bool LinkedList::isEmpty()
{
    return first->next == NULL;
}

/*
* Prints the list elements.
*/
void LinkedList::display()
{
    Node * current = first->next;

    while (current != NULL)
    {
        cout << current->info << " ";
        current = current->next;
    }

    cout << endl;
}
void LinkedList::displayLast()
{
    Node *current = last;
    while (current != NULL)
    {
        cout << current->info << " ";
        current = current->prev;
    }
    cout << endl;
}

/*
* Adds the element x to the beginning of the list.
*
* x: element to be added to the list.
*/
void LinkedList::add(int x)
{
    Node *p = new Node;

    p->info = x;
    p->next = first->next;
    p->prev = last;
    first->next = p;
    last = p;
}
void LinkedList::addEnd(int x)
{
    Node *p = new Node;
    p->info = x;
    p->prev = last;
    last->next = p;
    last = p;
}


/*
* Removes the first occurrence of x from the list. If x is not found,
* the list remains unchanged.
*
* x: element to be removed from the list.
*/
void LinkedList::remove(int x)
{
    Node * old = first->next,
        *p = first;

    //Finding the address of the node before the one to be deleted
    bool found = false;
    while (old != NULL && !found)
    {
        if (old->info == x) found = true;
        else
        {
            p = old;
            old = p->next;
        }
    }

    //if x is in the list, remove it.
    if (found)
    {
        p->next = old->next;
        delete old;
    }
}

这是。文件:

class LinkedList
{
public:
    LinkedList();
    ~LinkedList();
    bool isEmpty();
    void display();
    void add(int);
    void remove(int);
    void addEnd(int);
    void displayLast();

private:
    Node * first;   //pointer to header (dummy) node
    Node *last;
};

0 个答案:

没有答案