您的位置:首页 > 编程语言 > C语言/C++

C++ 单链表实现

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

头文件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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: