链表操作

#include <iostream>
using namespace std;
//链表的定义
typedef int T;
class List {
struct Node {
	T data;
	Node* next;
	Node (const T & t=T()):data(t)
	{next=NULL;}
};
Node* head;
public :
List(): head (NULL) {}
void clear(){
while (head!=NULL) {
Node* q=head->next;
delete head;
head=q;
}
}
~List (){clear();}
//从前插入链表元素
void insert_front(const T & t)
{
	Node* p=new Node(t);
	p->next=head;
	head=p;
}
//遍历链表元素
void travel()
{
	Node *p=head;
	while(p!=NULL){
		cout<<p->data<<' ';
		p=p->next;
	}
	cout<<endl;
}
//链表元素的个数
int size() {
int cnt=0;
Node* p=head;
while (p!=NULL)
{
cnt++;
p=p->next;
}
return cnt;
}
//取得链表的头结点
T GetHead () {
if(head==NULL)
throw "no head";
return head->data;
}
//取得链表的尾结点
T gettail () {
if(head==NULL)
throw "no tail";
Node* p=head;
while(p->next!=NULL)
p=p->next;
return p->data;
}
//清空链表
bool empty (){
return head==NULL;
}
//查找链表中的某个元素
int find (const T & t) {
Node* p=head;
int pos=0;
while(p!=NULL) {
if(p->data==t)
return pos;
p=p->next;
pos++;
}
return -1;
}
//修改链表中的某元素
bool update (const T & o,const T &n) {
int pos=find(o);
if(pos==-1)
return false;
Node* p=getPointer(pos);
p->data=n;
return true;
}
 private:
Node* getPointer(int pos) {
Node* p=head;
for(int i=0;i<pos;i++)
p=p->next;
return p;
}
//删除链表中的某个元素
public:
bool erase(const T & t) {
int pos=find(t);
if(pos==-1)
return false;
if(pos==0) {
Node* q=head->next;
head=q;
}
else
{
	Node* pre=getPointer(pos-1);
	Node* cur=pre->next;
	pre->next=cur->next;
}
}
};
int main()
{
	List obj;
	obj.insert_front(1);
	obj.insert_front(2);
	obj.insert_front(3);
	obj.insert_front(4);
	obj.insert_front(5);
	cout<<"size:"<<obj.size()<<endl;
	obj.travel();
	cout<<"find 3:"<<obj.find(3)<<endl;
	cout<<"find 8:"<<obj.find(8)<<endl;
	obj.update(4,100);
	obj.travel();
	obj.erase(3);
	obj.erase(5);
	obj.erase(1);
	obj.travel();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值