Cracking The Coding Interview 2.2

#include <iostream>
#include <string>
using namespace std;
class linklist
{
private:
	class node
	{
	public:
		node(){}
		string data;
		node * next;
	};
	node *head;
	int size;
public:
	linklist()
	{
		head = new node;
		size = 0;
	}
	/***整表创建***/
	void Create(string *s,int size)
	{
		if (s==NULL || size == 0)
		{
			return;
		}

		node *p = new node;
		p->data = s[0];
		head->next = p;

		for (int i = 1; i<size; i++)
		{
			node *t = new node;
			t->data = s[i];
			p->next = t;
			p=p->next;
		}
		p->next = NULL;
		this->size = size;
	}
	/***整表删除***/
	void Clear()
	{
		for (int i = 1;i<size+1; i++)
		{
			Delete(i);
		}
		head = NULL;
		size = 0;
	}

	
	/***第i[i为1,2....size,下同]个元素前插入string型e***/
	void Insert(int i, string e)
	{
		if (i<0 || i>size)
		{
			return;
		}
		int t = i - 1;
		node *p = head;
		node *pn = p->next;
		while(t!=0)
		{
			p = p->next;
			pn = pn->next;
			t--;
		}

		node *ee = new node;
		ee->data = e;
		ee->next = pn;
		p->next = ee;

		size ++;

	}

	/****获取第i个元素的值,并返回该值**/
	string Get(int i)
	{
		if (i<=0 || i>size)
		{
			return "Error: You input wrong num.";
		}
		int t = i;
		node *p =head;
		while(t!=0)
		{
			p = p->next;
			t--;
		}
		return p->data;
	}

	/***删除第i个元素***/
	void Delete(int i)
	{
		if (i<0 || i>size)
		{
			return;
		}
		int t = i - 1;
		node *p = head;
		node *pn = p->next;
		while(t!=0)
		{
			p = p->next;
			pn = pn->next;
			t--;
		}
		p->next = pn->next;
		delete pn;
		size --;
	}

	void Display()
	{
		if (head==NULL)
		{
			return;
		}
		node * p;
		p=head->next;
		/*for (int i =0; i<size; i++)
		{
		cout<<p->data<<"  ";
		p=p->next;
		}*/
		
		while(p!=NULL)
		{
			cout<<p->data<<"  ";
			p=p->next;
		}
		cout<<endl;
	}

	~linklist()
	{

	}

	/*****Implement an algorithm to find the nth to last element of a singly linked list.*****/
	string GetLastN(int n)
	{
		if (n<0||n>size)
		{
			return "Error: Wrong Number";
		}
		
		int i = 0;
		node *p = head->next;
		node *q = head->next;
		while(i<n)
		{
			p=p->next;
			i++;
		}
		while(p!=NULL)
		{
			p=p->next;
			q=q->next;
		}
		return q->data;
	}
};

int main()
{
	string str[8]={"sos","OMG","sos","OMG","OMG","OMG","fof","fof"};
	linklist s;

	s.Create(str,8);
	s.Display();
	
	/*s.Insert(2,"bingo");
	s.Display();

	s.Delete(3);
	s.Display();

	cout<<s.Get(1)<<endl;

	s.Clear();
	s.Display();*/
	
	//s.RemoveDupulicate();
	cout<<s.GetLastN(6);
	//s.Display();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值