首页 > 编程语言 > 详细

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

时间:2014-11-08 15:16:28      阅读:205      评论:0      收藏:0      [点我收藏+]
#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;
}


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

原文:http://blog.csdn.net/qq_22335577/article/details/40920543

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!