リンクリストのノードを削除する際に問題があります。これは私のコードです(ただし、addElement
の機能は問題ありません)。リストトラフ入力のノードを初期化し、右側のノードを高い値で削除して修正したリストを印刷し、最後にリストを削除する関数を呼び出します。 問題は、特定の入力でプログラムが正しく動作しないことです。 たとえば1,2,3,4,3を入力した場合、出力は1と3(2番目の3つ)ですが、出力は1になります。リンクリストからノードを正しく削除できない
何が問題になりますか?それを理解しているようには見えない。
編集1:以下が含まれます。 編集2:あなたのコードは動作しませんなぜ
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
struct digits {
int value;
digits *next
};
int main() {
int a, b, c;
digits *head = NULL, *tale = NULL, *current;
cout << "How many digits you want in the linked list?" << endl;
cin >> a;
for (int i = 0; i < a; i++) {
cin >> b;
current = new digits;
current->value = b;
current->next = NULL;
if (head == NULL)
head = tale = current;
else {
tale->next = current;
tale = current;
}
if (!cin.good()) {
cin.clear();
cin.ignore(256, '\n');
cout << "Input can be int value! You can still input " << (a - i) - 1
<< " digits." << endl;
continue;
}
}
cout << "Want to add element? Press J if so, otherwise any other key" << endl;
cin >> add;
if (add == 'J') {
cin >> c;
addElement(&head, c);
}
removeElement(head);
for (current = head; current != NULL; current = current->next)
cout << current->value << endl;
current = head;
while (current != NULL) {
head = head->next;
delete current;
current = head;
}
}
// function which removes elements which have greater value on right side
void removeElement(struct digits *head) {
struct digits *current = head;
struct digits *max = head;
struct digits *temp;
while (current != NULL && current->next != NULL) {
if (current->next->value > max->value) {
temp = current->next;
current->next = temp->next;
free(temp);
} else {
current = current->next;
max = current;
}
}
}
void addElement(struct digits **head, int a) {
struct digits *newelem = (struct digits*) malloc(sizeof (struct digits));
newelem->value = a;
newelem->next = NULL;
struct digits *temp = *head;
if (*head == NULL) {
*head = newelem;
} else {
while (temp->next != NULL)
temp = temp->next;
temp->next = newelem;
}
}
空きと新しく混在させないでください - 削除は新しい – UKMonkey
に一致する呼び出しですこれはすべてが含まれていません。また、フォーマッタを使用してください。あなたが本当に '}}'を書くか、 'struct main'の宣言の後に' int main() 'を置くと、あなたのコードの構造を推論するのは難しくなります。 – Zeta
@RawN一方で、C++は 'std'の上で学ぶべきです。一方、C++開発者は特定の(あまりにも高い)レベルを過ぎても、 'std'が何をしているのか理解し、同様のことを行うことができます(あまり最適化されていません)。 – Angew