我试图返回链表中的数据以将其存储在变量中,或者直接在另一个函数中使用它,但是我不知道如何实现。
#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函数时遇到麻烦,如果有人可以帮助我,那就太好了。我感谢任何帮助。
答案 0 :(得分:0)
您可以使用std :: list,它已经包含在C ++中。您可以使用at
来访问第n个元素。
答案 1 :(得分:0)
也许您遇到麻烦,因为如果列表为空,则GetNth()不会返回值。
node<Object> GetNth(){
node<Object> *current = head;
while(current != NULL)
if(current->next == NULL){
return current->data;
}
return NULL;
}