我试图找到包含最小值的节点和包含最大值的节点之间的距离。我提到这是一个线性双链表。我写的代码并没有解决我的问题,因为它应该和我没有找到任何其他的逻辑。在线性双链表中找到两个节点之间的距离(C++)
下面的代码:
#include<iostream>
#include<stdio.h>
struct Nod {
int info;
Nod* next;
Nod* prev;
};
Nod* createNode(int nr) {
Nod* nod = new Nod;
nod->info = nr;
nod->next = NULL;
nod->prev = NULL;
return nod;
}
bool checkDuplicates(Nod* lst, int nr) {
Nod* tmp = lst;
while (tmp != NULL) {
if (tmp->info == nr) {
return true;
}
tmp = tmp->next;
}
return false;
}
void insertNode(Nod*& lst, Nod* nou) { //at the beginning
if (lst == NULL) {
lst = nou;
}
else {
if (checkDuplicates(lst, nou->info) == false) {
nou->next = lst;
lst->prev = nou;
lst = nou;
}
else {
printf("Valoarea (%d) exista deja! \n", nou->info);
}
}
}
void printList(Nod* lst) {
Nod* tmp = lst;
if (tmp) {
while (tmp != NULL) {
printf("%d \n", tmp->info);
tmp = tmp->next;
}
}
}
void distance(Nod* lst) {
if (lst) {
/*Finding min and max*/
Nod* tmp = lst;
int min = tmp->info;
int max = tmp->info;
int poz_min = 1;
int poz_max = 1;
while (tmp != NULL) {
if (tmp->info < min) {
min = tmp->info;
poz_min++;
}
if (tmp->info > max) {
max = tmp->info;
poz_max++;
}
else {
tmp = tmp->next;
}
}
int dist = poz_max-poz_min;
if (dist<0) {
dist = dist*(-1);
}
printf("\n Min: %d [poz: %d] , Max: %d [poz: %d], Distance: %d. \n ", min, poz_min, max, poz_max, dist);
}
else {
printf("Null list.\n");
}
}
void main() {
Nod* lst = nullptr;
Nod* nou = createNode(5);
insertNode(lst, nou);
nou = createNode(2);
insertNode(lst, nou);
nou = createNode(1);
insertNode(lst, nou);
nou = createNode(7);
insertNode(lst, nou);
printList(lst);
distance(lst);
}
*我写的代码并没有解决我的问题,因为它应该* - 好吧,你用调试器来找出代码违背你的逻辑/计划的地方吗? - *我没有发现任何其他逻辑* - 如果他们这样说,那会让程序员从他们的工作中解雇。您编写了代码,找到代码违反计划的地方,并调整您的计划。 – PaulMcKenzie
@PaulMcKenzie您好!感谢您的回复!是的,我使用过调试器,但它对我没有帮助。这就是为什么我来这里提出一些建议。 – Alin
调试器的工作是逐步向你展示你的程序在做什么,变量的价值等。它不知道你想要解决什么问题 - 这就是你要确定的。如果一个变量有一个你没有想到的值,或者程序的路径与你期望的不同,那么你知道你有一个bug。 – PaulMcKenzie