【发布时间】:2017-11-17 15:58:20
【问题描述】:
我目前正在尝试为自己编写一个数据结构框架。在普通情况下,从单链表中删除第二大节点完美无缺。但在一个特定的方面失败了。这是我已经尝试过的:
//node.h
typedef struct Node {
int value;
struct Node *nextNode;
} Node;
//linkedlist.h
typedef struct LinkedList{
Node *head;
int count;
} LinkedList;
//liblinkedlist.c
int deleteSecondLargest(LinkedList *list){
if(list->count==0)
return 1;
if(list->count==1)
return 2;
Node *temp = list->head;
Node *largest = temp;
Node *prev = NULL;
Node *prev1 = NULL;
Node *ptr = temp;
//finding the second largest node
while(temp!=NULL){
if(temp->value > largest->value){
largest = temp;
}
else if((temp->value!=largest->value) && (temp->value > ptr->value)){//here's the code failing
prev1 = prev;
ptr = temp;
}
prev = temp;
temp = temp->nextNode;
}
//deleting it
if(ptr==list->head)
list->head = list->head->nextNode;
else
prev1->nextNode = ptr->nextNode;
free(ptr);
list->count--;
return 0;
}
只要列表中的项目按 1332->34->N 的顺序排列,注释块中的代码就会失败。
我可以理解为什么它失败了,因为 temp 和 ptr 都持有 1332 而 else if 在第二次迭代中返回 false,但我找不到任何解决方案。此外,函数所在的文件已在函数定义上方进行了注释。
有什么帮助吗?
【问题讨论】:
-
请修改您的代码以获得minimal reproducible example。
-
单步执行我脑海中的代码(根据您显示的示例列表),就我所见,它应该可以正常工作。您能否详细说明“失败”部分? 如何失败了?您是否在调试器中逐行执行代码(直到函数结束)?
-
@alexeykuzmin0 如果我理解正确的话,这已经在方法中完成了。我已经更新了 cmets。立即查看。
-
@Someprogrammerdude 当节点为 1334 和 34 时,代码将失败。temp 和 ptr 都被初始化为 1334。现在在 while 循环中,在第二次迭代中,
else if分支应该为 true我的代码工作。但这并不是ptr持有1334和temp持有34。temp不大于ptr,因此整个分支失败。 -
在 temp 和 ptr 都等于 1332 的步骤中,if 语句在到达 isValueGreater 部分之前不应该失败吗?因为两者都相等,所以 isValueEqual 为真-> if 语句失败...
标签: c++ c data-structures linked-list singly-linked-list