c - 使用 c 在链表中的特定位置插入节点
问题描述
谁能告诉我哪里做错了。我是链表数据结构的新手,这是我的代码:
样本输入
3
16
13
7
1
2
样本输出
16 13 1 7
解释
初始链表是16 13 7
。我们必须在当前位置插入。更新后的链表将是16 13 1 7
SinglyLinkedListNode *insertNodeAtPosition(SinglyLinkedListNode *head, int data, int position) {
SinglyLinkedListNode *newNode = (SinglyLinkedListNode *)malloc(sizeof(SinglyLinkedListNode));
newNode->data = data;
if (head == NULL) {
return newNode;
}
if (position == 0) {
newNode->next = head;
return newNode;
}
SinglyLinkedListNode *currentNode = head;
while ((currentNode->next) != position) {
currentNode = currentNode->next;
}
newNode->next = currentNode->next;
currentNode->next = newNode;
return head;
}
错误的答案
你的输出(标准输出)~标准输出没有响应~
解决方案
这里
while((currentNode->next)!=position) {}
比较是不正确的,你是与不是的comapringint
类型currentNode->next
int
,编译器应该警告你是否已经使用适当的标志编译,如
gcc -Wall -Wextra -pedantic -Werroc test.c
试试这个版本
int itr = 0;
while(currentNode != NULL && itr < position) { /* iterate till position & until currentNode not NULL. both condition must satisfy */
currentNode=currentNode->next;
itr++;
}
推荐阅读
- android - 华为地图套件风格特征
- python - 从 numpy 数组映射回 pandas 时间序列的最佳方法
- django - 如何在 django import-export 中显示已清理的电子邮件数据
- python - 在 Python 中遍历目录
- javascript - 如何使用 PerformanceNavigationTiming API 来跟踪跨网络工作者和跨源 iframe 的任务持续时间?
- azure - MS Teams 上的绿色成功消息,用于缩略图/英雄卡中的 messageBack 操作类型
- java - 没有PDF保存功能的Android PDF打印
- android - Android Media Player:如何通过 url 离线播放音频?
- amazon-web-services - Cloudwatch Insight 查询以获取子任务的持续时间
- c# - Bamboo build 挂了 20 分钟