C++实现数据结构中的单链表

#include<iostream>
using namespace std;
//定义一个节点类
class Node{
public:
	int data;
	Node *next;
	Node():next(NULL){}
	Node(const int &value,Node *next_=NULL):data(value),next(next_){}

};
//定义一个单单链表
class Linklist{
private:
	Node *head;
public:
	Linklist():head(new Node){}
	//判断链表是否为空
	bool is_empty()const
	{
		if(head->next==NULL)
			return true;
		return false;
	}
	//判断链表的长度
	int get_length()
	{
		int length=0;
		Node *p=head->next;
		while(!p)
		{
			++length;
			p=p->next;
		}
		return length;	
	}
	//返回第i=个元素的值
	Node *get_value(int i)
	{
		if(i<=0||i>get_length())
		{
			cout<<"error"<<endl;
			return NULL;
		}
		else
		{
			Node *p=head->next;
			int j=1;
			while(p&&j<i)
			{
				p=p->next;
				++j;
			}
			return p;
		}
	}
  //在第i个位置之前插入相应元素的值
	bool insert_pos(int value,int i)
	{
		if(i<=0||i>get_length())
		{
			cout<<"无法插入相应的元素"<<endl;
			return false;
		}
		else
		{
			int j=1;
			Node *p=head;
			while(p&&j<i)
			{
				p=p->next;
				++j;
			}
			Node *newnode=new Node(value);
			newnode->next=p->next;
			p->next=newnode;
			return true;
		}
	}
	//下面顶一个采用尾插法插值的函数
	void insert(int value)
	{
		Node *p=head;
		Node *q=p;
		while(p)
		{   q=p;
			p=p->next;
		}
		Node *newnode=new Node(value);
		q->next=newnode;
	}

	void display()
	{   
		if(head->next==NULL)
			return ;
		Node *p=head->next;
		while(p)
		{
			cout<<p->data<<'\t';
			p=p->next;
		}
	}
	//定义一个删除某个节点的函数
	void delete_node(int value)
	{
		Node *pos_node=NULL;
		Node *q=head;
		Node *p=head->next;
		while(p)
		{
			if(p->data==value)
			{
				pos_node=p;
				break;
			}
			q=p;
			p=p->next;
		}
		if(!p)
		{
			cout<<"找不到要删除的结点"<<endl;
			return ;
		}
		Node *s;
		q->next=pos_node->next;

	}

};

int main()
{   
	Linklist l1;
	l1.insert(1);
	l1.insert(2);
	l1.insert(3);
	l1.insert(4);
	l1.insert(5);
	l1.insert(6);
	l1.insert(7);
	l1.display();
	cout<<endl;
	l1.delete_node(4);
	l1.display();
	system("pause");
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值