【发布时间】:2025-12-25 04:35:12
【问题描述】:
我正在尝试合并两个双向链表。我已经创建了一个以正确顺序插入新节点的函数。参数由我的教授设置,所以我无法更改。我能够将第一项添加到 List1 但无法再添加。
我在尝试继续遍历 List2 并向 List1 添加更多项目时遇到错误。我尝试过递归和 do while 循环。在尝试使用 do-while 循环时
struct nodeType{
int info;
nodeType *next;
nodeType *back;
};
class OrderedDoublyLinkedList{
public:
//Insert x in appropriate place in the list to keep it
sorted
void insertNode(int x);
void mergeLists(OrderedDoublyLinkedList &List1,
OrderedDoublyLinkedList &List2);
private:
int count;
nodeType *first;
nodeType *last;
};
void
OrderedDoublyLinkedList::mergeLists(OrderedDoublyLinkedList
&List1, OrderedDoublyLinkedList &List2){
//First Technique
do{
List1.insertNode(List2.first->info);
List2.first->next; //Error: Expresion result unused
}
while(List2.first!=NULL)
//Second Technique
while(List2.first!=NULL)
List1.insertNode(List2.first->info);
mergeLists(&List1, &List2.first->next);
//If I try to use this it says cannot bind to a temporary of
type
我需要帮助访问下一个节点以将其余信息添加到 List1。
【问题讨论】:
-
我们先从基础开始,合并两个列表是什么意思?例如,您是否尝试通过合并两个列表来创建第三个列表?您是否尝试将第二个列表合并到第一个列表(或相反)?很多时候,merge这个词意味着节点是一个列表被移动(而不是复制)到另一个列表,即没有分配新节点并且第二个列表通过将节点移动到第一个而被破坏。这里是这样吗?这些细节很重要,因此您确实需要准确指定您期望
mergeLists做什么。添加一些您期望的输入和输出示例。 -
您在两次尝试中没有解决的一个问题是合并列表应该是ordered。所以这个问题的任何解决方案都需要将第一个列表上的节点与第二个列表上的节点进行比较,这样才能保持正确的排序。因此,您需要在代码中的某处比较两个列表的
info字段。 -
我必须将 List2 移动到 List1 中。 insert 函数创建新节点,然后将其按正确顺序放置,因此无需比较
-
好吧,这效率很低,但我想这是你被告知要做的。
-
我没有包含该功能,因为我不希望它太长。不是我最担心尝试访问下一个链接
标签: c++ linked-list doubly-linked-list