加工(单链表)

1、题目:


 Problem Description

对一串手链进行加工,起始时,该手链有n(1,2,....n)个的珠子,珠子都有颜色color(字符串,长度<=15)。
对手链加工的方法有4种:
ADD:在手链上的末尾添加一个珠子
DELETE:将手链上的第x个珠子除去
REPLACE: 将手链上的第x个珠子替换掉
FINISH:加工完毕,将珠子的颜色输出
要求若x值非法,则相应的命令无效,不执行。
要求用单链表完成!!!否则答案无效!!!

 Input

输入数据多组,每组多行
第一行为一个正整数n(0<n<10),代表手链有n个的珠子
接下去有n行字符串,为珠子的颜色
接下去还有多行加工指令
加工指令格式:
添加:ADD color
删除:DELETE x
替换:REPLACE x color
加工完成:FINISH

 Output

每组输出数据均占一行
输出手链珠子的颜色,颜色之间有一个空格

 Sample Input

3
red
pink
purple
ADD white
DELETE 2
ADD green
REPLACE 4 black
FINISH

 Sample Output

red purple white black

 Author

hdf


2、参考代码:


#include <iostream>
#include <string>
using namespace std;

struct Node{
	string data;
	Node* next;
};

class LinkList{
private:
	Node* head;
	Node* Creat(int t);
	void Del(Node* p);
public:
	LinkList(int t);
	~LinkList();
	void ADD();
	void DELETE();
	void REPLACE();
	void show();
};

Node* LinkList::Creat(int t){
	string str;
	Node* r,* s;
	head=new Node;
	r=head;
	while(t--){
		cin>>str;
		s=new Node;
		s->data=str;
		r->next=s;
		r=s;
	}
	r->next=NULL;
	return head;
}

void LinkList::Del(Node* p){
	if(p)
		Del(p->next);
	delete p;
}

LinkList::LinkList(int t){
	head=Creat(t);
}

LinkList::~LinkList(){
	Del(head);
}

void LinkList::ADD(){
	Node* r,* s; 
	string str;
	cin>>str;
	r=head;
	while(r->next)
		r=r->next;
	s=new Node;
	s->data=str;
	s->next=r->next;
	r->next=s;
	r=s;
}

void LinkList::DELETE(){
	int x,count=0;
	cin>>x;
	Node* p,* q;
	q=head;
	p=q->next;
	while(p)
	{
		if(count==x-1)
		{
			q->next=p->next;
			delete p;
			break;
		}
		q=p;
		p=p->next;
		count++;
	}
}

void LinkList::REPLACE(){
	int count=0,x;
	string str;
	Node* p,* q;
	cin>>x>>str;
	q=head;
	p=q->next;
	while(p)
	{
		if(count==x-1)
		{
			p->data=str;
			break;
		}
		q=p;
		p=p->next;
		count++;
	}
}

void LinkList::show(){
	Node* p=head->next;
	if(p){
		cout<<p->data;
		p=p->next;
		while(p){
			cout<<" "<<p->data;
			p=p->next;
		}
	}
	cout<<endl;   ///注意题目所说的“每组输出数据均占一行”
}

int main()
{
	int t;
	string a;
	while(cin>>t)
	{
		LinkList w(t);
		while(cin>>a)
		{
			if(a=="FINISH")
			{
				w.show();
				break;
			}
			else if(a=="ADD"){
				w.ADD();
			}
			else if(a=="DELETE")
				w.DELETE();
			else if(a=="REPLACE")
				w.REPLACE();
		}
	}
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值