10-4 写一个类使之成为可以存储strings的链表。
10-5 为上面的String_list 类写一个双向迭代器。
10-6 为了检验上面的类,重写split函数将结果输入到String_list类中。
这三个题目都是针对一个类进行操作的,所以将这三道题在一个程序中实现。
分析:因为题目要求编写一个string类型的链表,所以程序必须先定义一个结点Node的结构体和一个String_list类。但是由于上学期教我们C的老师比较无语,直接跳过了链表这一章,而我一直是一个主动性不强的人,虽然一直说要自学这部分,看了书,没实际敲过链表的实现,所以这道题目拿到手是很悲催,一直等到看了老师的讲解后才按照老师说的敲了个代码,,好吧,鄙视我把= =
代码:
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
struct Node
{
string data;
Node *cur;
Node *next;
};
class String_list
{
public:
String_list(){head=NULL;}
void Insert(string str);
void Input();
private:
Node *head;
};
void String_list::Insert(string str)
{
Node *s;
Node *current;
s=(Node*)new(Node);
s->data=str;
if(head==NULL)
{
s->next=NULL;
head=s;
head->cur =NULL;
}
else
{
current=head;
while(current->next!=NULL)
current=current->next ;
current->next=s;
s->next=NULL;
s->cur=current;
}
}
void String_list::Input()
{
Node *p,*q;
p=head;
q=head;
int i=0,j=0;
cout<<"original sequence:";
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
++i;
}
cout<<endl<<endl;
cout<<"reverse sequence:";
while(j!=i-1)
{
q=q->next;
++j;
}
while(q!=NULL)
{
cout<<q->data<<" ";
q=q->cur;
}
}
String_list split(const string& s)
{
String_list ret; //有改变
typedef string::size_type string_size;
string_size i=0;
while(i!=s.size())
{
while(i!=s.size()&&isspace(s[i]))
++i;
string_size j=i;
while(j!=s.size()&&!isspace(s[j]))
++j;
if(i!=j)
{
ret.Insert(s.substr(i,j-i)); //看清楚这里
i=j;
}
}
return ret;
}
int main()
{
string s;
getline(cin,s);
cout<<endl;
String_list lis;
lis=split(s);
lis.Input();
return 0;
}
运行结果: