c++ - 用 2 个指针反转链表
问题描述
我正在尝试仅使用两个指针创建一个链接列表(我查看的每个帖子似乎都使用 3,但我对分配的要求是 2)
所以我将从我如何处理这个问题开始。目前这些值是这样链接的 nullptr -> (head)1->2-> ... -> 7->8->nullptr,其中被反转的值是 1,2,3,4,5,6, 7,8
void reverseList(){
ListNode *last = head;
ListNode *current = last->next;
if(current == nullptr) return;
while(current != nullptr){
current->next = last;
last = current;
current = last->next;
}
}
从逻辑上讲,在纸上我的循环是有效的,但在我的 ide 和调试器中它是一个无限循环。
我还尝试制作一个循环来检查大小并从最后开始,其中 head = 8 和 tail = 1 但这也不起作用。
我还尝试了一种二分搜索方法,在该方法中找到了中点并进行了 +- mid 并交换了,但我也无法从 4->3 开始。
我的目标是从 1->2->3->4->5->6->7->8 到 8->7->6->5->4->3->2 ->1
解决方案
让它更简单,head
而是移动 ptr 。
由于您display()
首先在head
.
void reverseList(){
ListNode* current = head->next;
if(current == nullptr) return; // list is empty
head->next = nullptr;
while(current != nullptr) { // have we reached the end of a forward list?
ListNode* next = current->next;
current->next = head; // reverse next pointer to "previous" node
head = current; // move last pointer to "current" node
current = next; // move to "next" node
}
}
推荐阅读
- google-cloud-platform - 如何在 GCP BigQuery 联合查询中使用查询参数
- c# - 如何降低 dockerized .Net Core 应用程序的大小?
- r - IF else by group - 检查下一行的值
- caching - aws cloudformation CachePolicy 通用错误
- python - Keras model.evaluate 使用 ImageDataGenerator 时的准确率停留在 50%
- javascript - Discord.js v12 Ban 命令有效但不禁止成员
- javascript - 为什么我的节点包管理器在安装它并运行 pacakage.JSON 文件后给我错误?
- javascript - 源地图未在 Google Chrome 中激活
- python - 彩色图像上卷积滤波器后输出张量的形状
- opencv - 如何检测连续图像