c++数据结构 单链表的实现
来源:互联网 发布:网络借贷平台监管办法 编辑:程序博客网 时间:2024/06/05 18:47
linklist.h
#ifndef linklist_h#define linklist_htemplate<class t>struct node{ t data; node<t>*next;};template<class t>class linklist{public: linklist(); linklist(t a[], int n); ~linklist(); int locate(t x); void insert(int i, t x); t del(int i); void printlist();private: node<t>*first;};#endif
linklist.cpp
#include<iostream>using namespace std;#include"linklist.h"template<class t>linklist<t>::linklist(){ first = new node<t>; first->next = NULL;}template<class t>linklist<t>::linklist(t a[], int n){ node<t>*r, *s; first = new node<t>; r = first; for (int i = 0; i < n; i++) { s = new node<t>; s->data = a[i]; r->next = s; r = s; } r->next = NULL;}template<class t>linklist<t>::~linklist()//释放所有结点包括头结点{ node<t>*q = NULL; while (first != NULL) { q = first; first = first->next; delete q; }}template<class t>void linklist<t>::insert(int i, t x){ node<t>*p = first, *s = NULL; int count = 0; while (p != NULL&&count < i - 1) { p = p->next; count++; } if (p == NULL)throw"位置"; else { s = new node<t>; s->data = x; s->next = p->next; p->next = s; }}template<class t>t linklist<t>::del(int i){ node<t>*p = first, *q = NULL; t x; int count = 0; while (p != NULL&&count < i - 1) { p = p->next; count++; } if (p == NULL||p->next==NULL)throw"位置"; else { q = p->next; x = q->data; p->next = q->next; delete q; return x; }}template<class t>int linklist<t>::locate(t x){ node<t>*p = first->next; int count = 1; while (p != NULL) { if (p->data == x)return count; p = p->next; count++; } return 0;}template<class t>void linklist<t>::printlist(){ node<t>*p = first->next; while (p != NULL) { cout <<p->data<< " "; p = p->next; } cout << endl;}
linklist_main.cpp
#include<iostream>using namespace std;#include"linklist.cpp"int main(){ int r[5] = { 1, 2, 3, 4, 5 }; linklist<int>l(r, 5); cout << "插入前数据为"<< endl; l.printlist(); l.insert(2, 3); cout << "插入后数据为" << endl; l.printlist(); cout << "位置为5的元素位置为"<< endl; cout << l.locate(5) << endl; cout << "删除前数据为"<< endl; l.printlist(); l.del(1); cout << "删除后数据为"<< endl; l.printlist(); return 0;}
0 0
- 数据结构---单链表c实现
- 数据结构--单链表C实现
- 数据结构C语言版单链表的实现
- <数据结构>单链表的C语言实现
- 数据结构C语言版--单链表的基本功能实现
- C语言数据结构单链表的实现
- 数据结构之单链表的C语言实现
- [数据结构]单链表C语言的简单实现
- 【数据结构】数据结构C语言的实现(单链表)
- 数据结构中单链表的实现+单链表的C语言实现源代码
- 数据结构.单链表(C语言实现)
- 数据结构:单链表排序--C实现
- 数据结构(C实现)------- 单链表
- 数据结构--单链表c语言实现
- 【数据结构】实现单链表(c++)
- 【数据结构】C语言实现单链表
- C/C++,数据结构单链表实现约瑟夫环
- 数据结构——单链表的实现——C语言版
- bzoj4521 [Cqoi2016]手机号码 (数位DP)
- Java面试题全集(中)
- SQL
- Node后端数据渲染
- 程序员的编程语言迁移路线:Go语言是最大赢家,Java 还在,Perl 灭亡了,Rust 做的相当不错。
- c++数据结构 单链表的实现
- JavaScript 函数调用
- SpringMVC将表单对象序列化成Json字符串提交,以List接收
- 从数据库、代码和服务器对PHP网站Mysql做性能优化
- JAVA开发之 5-常见错误的处理
- 最长公共子序列与最长公共子串
- maven install 程序包不存在
- Java面试题全集(下)
- Openstack安装前需要做的工作