C++ 单链表实现

来源:互联网 发布:java多线程抢票 编辑:程序博客网 时间:2024/06/03 08:00



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

头文件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);//查找链表是否含有keyint numOfKey(int key);//返回key在链表中的位置void insert(int key);//在链表结尾插入key    void insertElem(int i, int key);//在位置i插入数据keyint 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函数判断链表是否包含keynode *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;}


原创粉丝点击