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;
}
運行結果: