Accelerated C++第十章课后习题(下)

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;
}


运行结果:

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值