c++ - c++ 在不改变原始链表的情况下反转链表
问题描述
我正在尝试反转链表,但我不想更改通过引用传入的原始链表,我该如何解决?
typedef Node * ListType
ListType reverse(ListType list) {
if (list == NULL) {
return list;
}
ListType curr = list;
//printList(list); //list unchanged
ListType prev=NULL, next=NULL;
while (curr != NULL) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
//printList(list); //list changed(I dont't want it changed)
return prev;
}
解决方案
由于您不想更改原始列表,因此您必须对其进行复制。遍历原始列表,将新节点添加到反向列表中,然后返回它。
例如:
typedef Node* ListType;
ListType reverse(ListType list) {
if (!list) {
return NULL;
}
//printList(list); //list unchanged
ListType curr = list, head = NULL, tail = NULL, copy;
ListType *n = &tail;
do {
copy = new Node;
copy->prev = NULL;
copy->next = head;
copy->data = curr->data; // copy your data field(s) as needed...
*n = copy;
n = &(copy->prev);
head = copy;
curr = curr->next;
}
while (curr);
//printList(list); //list still unchanged
return head;
}
只要确保调用者在使用它后释放返回的列表。
推荐阅读
- mysql - 如何在 Excel 上的查询中写入 NULL?
- asp.net - 使用后端和前端方法的 JWT 身份验证
- java - 使用 Collections.binarySearch() 进行谓词搜索(即不完全匹配)
- javascript - 如何从用 xml 字符包装的 json 访问数据?
- ruby - RubyMine 可以检测 _spec.rb 文件并在单击运行/调试时显示它们吗?
- objective-c - 从 NSPasteboard mac 获取剪贴板的对象
- rust - 如何生成随机 num::BigUint?
- firebase - Firebase 云功能节点折旧警告
- c# - 数组的反向排序
- dart - Flutter - 用于绘图书页面的 TextPainter 与段落