我是新來的雙向鏈表。我正在編寫幾段代碼:一個用於將項目添加到前端的功能,另一個用於將項目添加到後端的功能,以及用於從前到後輸出鏈接列表的前向和後向顯示方法,分別。
我在輸出中遇到了一個錯誤,我試圖理解。看來我的addFront和display功能正在工作,但我的addBack可能是我的錯誤所在。我發佈了我的輸出結果以及它在這篇文章的底部顯示的內容。 這是我迄今爲止的代碼。麻煩添加項目到雙向鏈表後面
#include<iostream>
using namespace std;
class doubleLinkedList
{
private:
class node
{
public:
int data;
node* next;
node* prev;
node(int x)
{
data = x;
next = NULL;
prev = NULL;
}
};
public:
node* head;
node* tail;
int count;
doubleLinkedList(); //default constructor
~doubleLinkedList(); //destructor
void displayForward(); //display items from front to back
void displayBackward(); //display items from back to front
void addFront(int); //add item to front of linked list
void addBack(int); //add item to back of linked list
int removeFront(); //remove item from front of linked list
int removeBack(); //remove item from back of linked list
};
//constructor
doubleLinkedList::doubleLinkedList(){
head = tail = NULL;
count = 0;
}
//destructor
doubleLinkedList::~doubleLinkedList(){
node* current = head;
while(current != NULL)
{
node* previous = current;
current = current->next;
delete previous;
}
head = tail = NULL;
count = 0;
}
//display items in linked list from front to back
void doubleLinkedList::displayForward(){
node* pCurrent = head;
while (pCurrent != NULL)
{
cout << pCurrent->data << " ";
pCurrent = pCurrent->next;
}
cout << count;
}
//display items in linked list from back to front
void doubleLinkedList::displayBackward(){
node* pCurrent = tail;
while (pCurrent != NULL)
{
cout <<pCurrent->data << " ";
pCurrent = pCurrent->prev;
}
cout << count;
}
//add item to front of linked list
void doubleLinkedList::addFront(int x){
node* n = new node(x);
n->next = head;
n->prev = NULL;
if (head != NULL)
head->prev = n;
head = n;
count++;
if (tail == NULL)
tail = n;
}
void doubleLinkedList::addBack(int x){
node* n = new node(x);
n->next = NULL;
n->prev = tail;
tail = n;
count++;
}
////////////////////我的測試代碼:///////////////////
int main()
{
doubleLinkedList list;
list.addBack(40);
list.addBack(50);
list.addBack(60);
list.addFront(30);
list.addFront(20);
list.addBack(70);
list.addBack(80);
list.addFront(10);
list.displayForward(); //10 20 30 8 (the 8 value is the count/size i'm keeping track of)
cout << endl;
list.displayBackward(); //80 70 60 50 40 8
cout << endl;
system("pause");
return 0;
}
我的輸出應該顯示10 20 30 40 50 60 70 80 和80 70 60 50 40 30 20 10
而是我displayForward顯示我加入到前面的項目和我的displayBackward顯示的項目我添加到後面。
你不應該讓tail->未來隨着n尾= N,在加回過嗎? – sajas