我試圖找到包含最小值的節點和包含最大值的節點之間的距離。我提到這是一個線性雙鏈表。我寫的代碼並沒有解決我的問題,因爲它應該和我沒有找到任何其他的邏輯。在線性雙鏈表中找到兩個節點之間的距離(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