教授によって定義されたタイプであるトークンのベクトルを取り、ベクトルの各要素をリンクリストに入力する関数を作成しようとしています。最初の要素の先頭を返します。new_list の最後の部分にある cout ステートメントは、実際にベクトルの要素をリンク リストに挿入していることを示しています。だから私が入力すると:
新しい a 9 2 3
9 2 3 挿入中
print_list_cmd は私の教授によって定義されており、new a を呼び出して作成したリストであると想定されているため、print a は 9 2 3 を返す必要がありますが、print と入力すると、リンクされたリストの最後の要素である 3 しか取得できません。
2 つの質問があります。私のコードはあまりエレガントではありません。リンクされたリストにトークンのベクトルを挿入するより良い方法はありますか? 2 印刷コマンドがリンクされたリストの最後の要素のみを返すのはなぜですか? また、入力をトークン化するレクサー クラスもありますが、コードが多いので挿入しませんでした。
struct Node {
int key;
Node* next;
Node(int k=0, Node* n=NULL) : key(k), next(n) {};
};
Node* new_list(const vector<Token>& tok_vec){
//int key;
Node *head;
Node *newHead;
Node *headPointer = NULL;
newHead = new Node;
newHead -> next = NULL;
head = NULL;
for(unsigned int i = 0 ; i < tok_vec.size() ; i++){
// newHead -> key = tok_vec.at(i).value;
string myStream = tok_vec.at(i).value;
istringstream buffer(myStream);
int value;
buffer >> value;
newHead -> key = value;
if(!head){
head = newHead;
}else{
headPointer = newHead;
while(headPointer -> next){
headPointer = headPointer -> next;
headPointer -> next = newHead;
}
}
cout << head->key << endl;
}
return head->key;
}
void print_list_cmd(Lexer lex){
Token tok = lex.next_token();
if (tok.type != IDENT || lex.has_more_token())
throw runtime_error("SYNTAX: print listname");
if (list_table.find(tok.value) == list_table.end())
throw runtime_error(tok.value + " not defined or already destroyed");
print_list(list_table[tok.value]);
}