我想寫一個反向打印功能作爲雙向鏈表的一部分。以下是我寫的相關功能:C++雙向鏈表反向打印
void PLAYER::AddNode(int addID, std::string addName){
nodePtr n = new node; //creates a new node pointer
n->next = NULL; //Make next null
n->prev = NULL; // this will set this to be the ending node
n->ID = addID; //These two lines pass the information into the node
n->name = addName; // ID# and Name Information
if(head != NULL){ // This checks to see if a list is set up.
curr = head; // Make this point to the head.
while(curr->next != NULL){ // Loops through until the NULL is found
curr = curr->next;
}
curr->next = n; //Make the currnet node point to N
n->prev = curr; //Make the previous node connect to curr
n->next = tail; // connect new node to the tail.
}
else{
head = n; //If there is no list, this makes N the first node.
}
這裏是要使用的函數原型的類。
class PLAYER
{
public: // Functions go inside PUBLIC
PLAYER();
void AddNode(int addID, std::string addName);
void DeleteNode(int delPlayer);
void SortNode();
void PrintList();
void InsertHead(int AddID, std::string addName);
void PrintReverse();
private: //Variables go into here
typedef struct node{
// ...
std::string name;
int ID;
node* next;
node* prev;
}* nodePtr;
nodePtr head, curr, temp, prev, test, tail;
};
最後我試圖創建一個反向遍歷函數向後打印。
void PLAYER::PrintReverse()
{
curr = head;
while(curr->next != NULL) //Get to the end of the list
{
curr = curr->next;
}
while(curr->prev != NULL) //Work backward and print out the contents
{
std::cout << curr->ID << " " << curr->name << endl;
curr = curr->prev;
}
}
我想什麼做的是PrintReverse()函數中有它通過尾指針初始化,但我不能爲了弄清楚功能添加到PrintReverse()和ADDNODE()來有尾部指向的新節點。
這是我在這裏發佈的第一個問題,我希望我覆蓋了我的所有基地。感謝您的幫助,我可以找到。
編輯:
謝謝你的所有輸入。我重新學習數據結構,是的,這是我自己強加的作業,開始讓邏輯再次流動。
今晚我回家後我會做出改變。
你的代碼有兩個問題:(i)你在哪裏初始化尾部? (ii)在AddNode中,爲什麼不直接使用tail,而不是迭代直到結束,(iii)在PrintReverse函數中,你的類中已經有了尾節點nodePtr,爲什麼不從那裏開始呢? –
根據你有多少編程經驗,實現一個雙向鏈表可能有點棘手。爲什麼不使用STL的列表容器? –
@AmmarHussain我認爲99%的鏈表問題是作業分配。 –