C++ 单链表实现
2013-07-09 19:15
302 查看
插入代码不太会操作,练习中。。最近对数据结构和算法导论感兴趣,自己实现的代码发一些上来,以后应该会用到吧
头文件MYLinkList.h
头文件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; }
相关文章推荐
- [C++] 利用模板的模板参数实现单链表
- c++实现单链表的各种操作
- 单链表反序(反转)C++实现
- 数据结构C++单链表的实现
- 单链表基础操作C++实现
- C++实现删除单链表节点的功能(源代码+截图)
- 单链表C++实现_0904
- C++实现单链表的创建、插入、删除、逆置操作
- 单链表的简单c++实现
- 单链表的基本操作(C++实现)
- 单链表的C++实现
- 单链表基础操作C++实现
- 用C++实现单链表的创建、逆置和输出 的两种方法
- C++单链表的设计与实现
- 单链表的复制——C++实现
- 数据结构学习第一篇--C++实现单链表模板
- 单链表的C++实现
- 一个单链表C++简单的实现版本-转自chinaunix
- 单链表的实现C++封装
- c++数据结构 单链表的实现