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;}
- 单链表(C#)实现
- 用C实现单链表
- C实现单链表
- C语言实现单链表
- 数据结构---单链表c实现
- C语言实现单链表
- 单链表的C实现
- C语言单链表实现
- 单链表实现(C++)
- C语言实现单链表
- 单链表C语言实现
- c语言单链表实现
- 单链表反转 c实现
- 单链表之C实现
- 单链表-C实现-初级
- 单链表 C语言实现
- 单链表实现-c
- 【C++】单链表的实现
- 应用程序无法启动,应用程序的并行配置不正确
- 不安装office的情况下第三方软件(开发语言)调用MODI(Microsoft Office Document Imaging)
- 暑假培训题
- hdu1874
- 函数式编程初探
- C++ 单链表实现
- hdu 3415 Max Sum of Max-K-sub-sequence
- android 程序检测是否安装其他一个程序
- 三种排序算法python源码——冒泡排序、插入排序、选择排序
- makefile编写粗略(部分)解读
- 喜欢的句子
- 处女作
- 黑马程序员----网络编程
- 我的Android进阶之旅------>RGB颜色查询对照表