C++ で単純なリンク リストを実装しようとしています。ノードを作成でき、ノード自体が正しくリンクされているようです。私の質問には listIterate() 関数が関係していますが、必要に応じてコード全体をここに添付しました。
#include <iostream>
using namespace std;
//Wrapper class which allows for easy list management
class LinkedList {
//Basic node struct
struct node {
int data;
node *link;
};
node *head; //Pointer to the head (also referred to as root) node, or the first node created.
node *current; //Pointer to the /latest/ node, or the node currently being operated on.
node *tail; //Pointer to the tail node, or the last node in the list.
public:
//Default constructor. Creates an empty list.
LinkedList() {
head = NULL;
current = NULL;
tail = NULL;
cout << "*** Linked list created. Head is NULL. ***\n";
}
//Default destructor. Use to remove the entire list from memory.
~LinkedList() {
while(head != NULL) {
node *n = head->link;
delete head;
head = n;
}
}
/*
appendNode()
Appends a new node to the end of the linked list. Set the end flag to true to set the last node to null, ending the list.
*/
void appendNode(int i) {
//If there are no nodes in the list, create a new node and point head to this new node.
if (head == NULL) {
node *n = new node;
n->data = i;
n->link = NULL;
head = n;
//head node initialized, and since it is ALSO the current and tail node (at this point), we must update our pointers
current = n;
tail = n;
cout << "New node with data (" << i << ") created. \n---\n";
} else {
//If there are nodes in the list, create a new node with inputted value.
node *n = new node;
n->data = i;
cout << "New node with data (" << i << ") created. \n";
//Now, link the previous node to this node.
current->link = n;
cout << "Node with value (" << current->data << ") linked to this node with value (" << i << "). \n---\n";
//Finally, set our "current" pointer to this newly created node.
current = n;
}
}
/*
listIterate()
Iterates through the entire list and prints every element.
*/
void listIterate() {
//cursor
node *p;
//Start by printing the head of the list.
cout << "Head - Value: (" << head->data << ") | Linked to: (" << head->link << ") \n";
p = head->link;
cout << *p;
}
};
int main() {
LinkedList List;
List.appendNode(0);
List.appendNode(10);
List.appendNode(20);
List.appendNode(30);
List.listIterate();
}
ここで、このメソッド listIterate() について説明します。
void listIterate() {
//cursor
node *p;
//Start by printing the head of the list.
cout << "Head - Value: (" << head->data << ") | Linked to: (" << head->link << ") \n";
p = head->link;
cout << *p;
}
コマンドcout << *p;
はエラーをスローしますが、これが理由だと思います。この時点で、 p はhead->link
、ヘッドノードのリンクフィールドを指す別のポインターである を指しています。head->link
ここで、プログラムのこの時点で p を逆参照すると、pが変数を指しているため、 実際の値が存在しないことがわかりました。
私にとっては、p を 2 回逆参照すると ( **p
)、ポインターが 2 回続くはずです ( p
-> head->link
-> リンクされたリストの 2 番目のノードの値 ( 10
)。ただし、p を 2 回逆参照すると、このエラーがスローされます。
LinkedListADT.cc:89: エラー: '** p' の 'operator*' に一致しません</pre>これが事実である理由を理解するのを手伝ってくれる人はいますか? これは違法な操作ですか?私がよく知らない別の方法で実行されますか?