C++ 单链表实现



插入代码不太会操作,练习中。。最近对数据结构和算法导论感兴趣,自己实现的代码发一些上来,以后应该会用到吧

头文件MYLinkList.h

//头文件MYLinkList.h
#pragma once
#include <iostream>
using namespace std;

typedef struct node 
{
	int data;
	struct node *next;
}node;

class MYLinkList
{
public:
	MYLinkList(void);
	~MYLinkList(void);

private:
	node *head;
	int listLength;

public:
	bool isEmpty();//判空
	int getLength();//返回链表长度
	int at(int i);//返回链表第i个节点数据
	bool find(int key);//查找链表是否含有key
	int numOfKey(int key);//返回key在链表中的位置
	void insert(int key);//在链表结尾插入key
    void insertElem(int i, int key);//在位置i插入数据key
	int deleteElem(int i);//返回病删除链表第i个元素
	bool mergeList(MYLinkList list);//将list连接到this结尾
};


//MYLinkList.cpp
#include "MYLinkList.h"

MYLinkList::MYLinkList(void)
{
	head = new node;
	head->data = NULL;
	head->next = NULL;
	listLength = 0;
}

MYLinkList::~MYLinkList(void)
{
}

bool MYLinkList::isEmpty()
{
	if(head->next==NULL)
		return true;
	else return false;
}

int MYLinkList::getLength()
{
	return listLength;
}

int MYLinkList::at(int i)
{
	if(head->next==NULL || i>listLength)
		return false;//这个地方是个瑕疵,应该抛出异常才更好  //		throw exception("Oh my god");
	node *p = head->next;
	int num = 1;
	while(num!=i)
	{
		num += 1;
		p=p->next;
	}
	return p->data;
}

bool MYLinkList::find(int key)
{
	if(head->next==NULL)
		return false;
	node *p = head->next;
	while((p->data!=key)&&(p->next!=NULL))
		p=p->next;
	if(p->data==key)
		return true;
	else return false;
}

int MYLinkList::numOfKey(int key)
{
	//调用该函数前先调用find函数判断链表是否包含key
	node *p = head->next;
	int num = 1;
	while(p->data!=key)
	{
		num += 1;
		p=p->next;
	}
	return num;
}

void MYLinkList::insert(int key)
{
	node *tem ;
	tem = new node;
	node *p;
	p = head;
	tem->data = key;
	tem->next=NULL;	
	while(p->next!=NULL)
		p=p->next;
	p->next = tem;
	listLength = listLength + 1;
}

void MYLinkList::insertElem(int i, int key)
{
	node *tem,*p;
	tem = new node;
	tem->data = key;
	int location = 0;
	p=head;
	while(location!=i-1)
	{
		p=p->next;
		location += 1;
	}
	tem->next = p->next;
	p->next = tem;
	listLength=listLength+1;
}

int MYLinkList::deleteElem(int i)
{
	node *pre,*p;
	int location = 1;
	pre = head;
	p=head->next;
	while(location!=i)
	{
		pre = p;
		p=p->next;
		location += 1;
	}
    pre->next = p->next;
	int key = p->data;
	delete p;
	listLength = listLength-1;
	return key;
}

bool MYLinkList::mergeList(MYLinkList list)
{
	if(list.isEmpty())
		return false;
	node *p = head;
	int length  = list.getLength();
	int i=1;
	while(i!=length)
	{
		node *tem = new node;
		tem->data = list.at(i);
		p->next = tem;
		p=p->next;
		++i;
	}
	listLength = listLength+length;
	return true;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值