【C++】链表的实现(二)

头文件:list.h

#include<iostream>
#include <stdlib.h>
struct Node
{
   int Data;
   Node*next;
};
class list
{
   Node*head;
   public:
   	list(){head=NULL;}
   	void insertlist(int aDate,int bDate);//链表结点的插入
   	void Deletelist(int aDate);//链表结点的删除
   	void Outputlist();//链表结点的输出
   	Node*Gethead()
   		{return head;}
};

函数实现文件 list.cpp

#include "list.h"
#include<iostream>
using namespace std;

void list::Outputlist()
{
	Node*current=head;
	while(current!=NULL)
	{
		cout<<current->Data<<" ";
		current=current->next;
	}
	cout<<endl;
}

void list::insertlist(int aDate,int bDate) //在节点a前面插入节点b
{
	Node*p,*q,*s; //p指向结点a,q指向结点a_k,s指向结点b
	s=(Node*)new(Node); //动态分配一个新结点
	s->Data=bDate; //设b为此结点
	p=head;
	if(head==NULL) //若是空表,使b作为第一个结点
	{
		head=s;
		s->next=NULL;
	}
	else if(p->Data==aDate) //若a是第一个结点
	{
		s->next=p;
		head=s;
	}
	else
	{
		while(p->Data!=aDate&&p->next!=NULL)//查找结点a
		{
			q=p;
			p=p->next;
		}
		if(p->Data==aDate) //若有结点a
		{
			q->next=s;
			s->next=p;
		}
		else //若没有结点a;
		{
			p->next=s;
			s->next=NULL;
		}
	}
}

void list::Deletelist(int aDate) //设aDate是要删除的结点a中的数据成员
{
	Node*p,*q; //p用于指向结点a,q用于指向结a的前一个结点
	p=head;
	if(p==NULL) //若是空表
	return;
	if(p->Data==aDate) //若a是第一个结点
	{
		head=p->next;
		delete p;
	}
	else
	{
		while(p->Data!=aDate&&p->next!=NULL) //查找结点a
		{
			q=p;
			p=p->next;
		}
		if(p->Data==aDate) //若有结点a
		{
		q->next=p->next;
		delete p;
		}
	}
}

主函数 mian.cpp

#include<iostream>
#include "list.h"
using namespace std;
int main(){
	list l;
    l.insertlist(1,1);
    l.insertlist(1,2);
    l.insertlist(1,4);
   // l.insertlist(1,1);
    l.insertlist(1,8);
    l.Outputlist();
    return 0}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值