我正在尝试返回链表中的数据以将其存储在变量中或直接在另一个函数中使用它,但我并不完全知道如何实现它。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
template <class Object>
struct node{
Object data;
node *next;
};
template <class Object>
class list{
private:
node<Object> *head, *tail;
public:
list(){
head=NULL;
tail=NULL;
}
void display(){
node<Object> *temp=new node<Object>;
temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
}
void createnode(Object value){
node<Object> *temp=new node<Object>;
temp->data=value;
temp->next=NULL;
if(head==NULL){
head=temp;
tail=temp;
temp=NULL;
}else{
tail->next=temp;
tail=temp;
}
}
void insert_start(Object value){
node<Object> *temp=new node<Object>;
temp->data=value;
temp->next=head;
head=temp;
}
node<Object> GetNth(){
node<Object> *current = head;
while(current != NULL)
if(current->next == NULL){
return current->data;
}
}
void delete_last(){
node<Object> *current=new node<Object>;
node<Object> *previous=new node<Object>;
current=head;
while(current->next!=NULL){
previous=current;
current=current->next;
}
tail=previous;
previous->next=NULL;
delete current;
}
};
int main(){
ifstream ifile;
ifile.open( "input.txt" );
char word[300];
ifile >> word;
char* token = strtok( word, "," );
list<string> kids;
list<string> tasks;
while ( token != NULL ) {
kids.createnode(token);
token = strtok( NULL, "," );
}
ifile >> word;
token = strtok(word, ",");
while (token != NULL) {
tasks.createnode(token);
token = strtok(NULL, ",");
}
int days;
cout << "Enter the number of days: ";
cin >> days;
tasks.display();
cout << endl;
int first = 0;
string nextTask;
while(first < days){
cout << "Day " << first + 1 << " ";
kids.display();
kids.insert_start(kids.GetNth());
kids.delete_last();
first++;
}
return 0;
}
该程序的目的是根据一天为每个孩子分配不同的任务。我目前在使用getNth功能时遇到问题,如果有人可以帮助我,那就太好了。我感谢任何形式的帮助。
也许你遇到了麻烦,因为如果列表为空,GetNth(( 不会返回值。
node<Object> GetNth(){
node<Object> *current = head;
while(current != NULL)
if(current->next == NULL){
return current->data;
}
return NULL;
}
您可以使用std::list,它已经包含在C++中。您可以使用at
来控制第 n 个元素。