0
我想按字母順序將某些人的名字插入到一個循環的雙向鏈表中,但我只能添加到三個,而我不是確定爲什麼發生這種情況。我將新節點傳遞給insert
函數,創建一個指向它的指針,並遍歷整個列表以找到正確的插入點。但是,如果名稱超過三個,則會刪除一個節點並插入另一個節點。有人能幫我解決這個問題嗎?尋找在一個圓形雙向鏈表中插入的正確位置
其他信息:
- 每個
Node
有兩個指針稱爲next
和prev
和string
稱爲data
作爲數據成員 - 的
List
類包含插入件和顯示功能,和一個頭指針,其指向一個虛擬頭節點。這頭節點的next
和prev
指針指向自身時List
初始化
這是插入功能,我已經寫了:
void List::insert(Node newObject)
{
Node *toInsert = &newObject;
Node *cur = head->next;
while((cur != head) && (newObject.data > cur->data))
{
cout << "Is this loop entered?" << endl;
cur = cur->next;
}
toInsert->next = cur;
toInsert->prev = cur->prev;
cur->prev = toInsert;
toInsert->prev->next = toInsert;
}
而且我main.cpp
:
#include "list.h"
#include "node.h"
using namespace std;
int main()
{
Node nikhil = Node("Nikhil");
Node kaustubh = Node("Kaustubh");
Node jon = Node("Jonathan");
Node james = Node("James");
Node elias = Node("Elias");
Node kenny = Node("Kenny");
List suiteMates;
suiteMates.insert(nikhil);
suiteMates.insert(kaustubh);
suiteMates.insert(jon);
suiteMates.insert(james);
suiteMates.insert(elias);
suiteMates.insert(kenny);
suiteMates.display();
}
感謝您的幫助! – rafafan2010