我正在尝试搜索节点,其中输出即节点的结果不止一个。所以我想创建一个新的双向链表并将这些新节点添加到其中。 但是只得到1个正确的结果,第二个给我我猜地址或那个节点或是错误。如图所示。
我的代码:
Order::Node* Order::searchByDate(string date) {
Node* cur = head;
Node* node = NULL;
cout << "\nSearching " << endl;
Sleep(400);
while (cur != NULL) {
if (cur->date == date) {
//create new node
Node* newNode = new Node;
newNode->prev = NULL;
newNode->next = cur;
//copy newNode to node(new linked list having all search result)
node = newNode;
node->prev = newNode;
node = newNode;
Sleep(400);
}
cur = cur->next;
}
return node;
}
显示功能:
Node* cur = searchByDate(date);
while (cur != NULL) {
cout << cur->orderid << "\t\t" << cur->date << "\t" << cur->cust.custId << endl;
cur = cur->next;
}
我可以将所有搜索到的节点添加到一个链接列表中的任何解决方案。
答案 0 :(得分:4)
新节点
对于现有搜索结果
保持另一个指向搜索结果开头的指针。作为方法的结果返回此起始节点。
试试这个
Order::Node* Order::searchByDate(string date) {
Node* cur = head;
Node* node = NULL;
Node* start = NULL;
while (cur != NULL) {
if (cur->date == date) {
//make a new node
Node* newNode = new Node(cur->date);
newNode->prev = NULL; //explicitly set to NULL
newNode->next = NULL; //explicitly set to NULL
if (node == NULL) {
//very first node
node = newNode;
start = node;
}
else {
//append new node to existing nodes
//see diagram below
node->next = newNode;
newNode->prev = node;
node = newNode;
}
}
cur = cur->next;
}
return start;
}