链表的基本操作(c++实现)
跟c语言不同点
1.结点建立方法与释放方法
2.c++类 加入了构造函数和析构函数
3.每个函数有略微改动
/*Keep on going Never give up*/ /* Author : Vinegar-Tree Lang : C++ Blog : https://blog.csdn.net/xxxxxiao123 Date :2020/10/4 19:32 */ //#pragma GCC optimize(3,"Ofast","inline") #include<bits/stdc++.h> //#define int long long #define endl '\n' #define Accepted 0 #define AK main() #define I_can signed using namespace std; const int maxn =1010; const int MaxN = 0x3f3f3f3f; const int MinN = 0xc0c0c00c; typedef long long ll; const int inf=0x3f3f3f3f; const ll mod=1e9+7; using namespace std; struct Node { //单链表储存结构 int date; Node* next; }; class List{ private: Node* list; public: List(){ list = new Node; //生成新结点作为其头节点 list->date = 0; list->next = NULL; } ~List(){ delete list; } void list_init(int n) { //创建单链表 p是在链表中移动的,r是指向尾节点的 Node* r = list; //创建尾指针,指向头节点 for (int i = 0; i < n; i++) { Node* p = new Node; //生成新结点 cin >> p->date; p->next = NULL; r->next = p; r = p; } } int list_find(int x) { //查找某个值在链表中的位置 Node* p = list->next; int cnt=0; while (p && p->date != x) p = p->next,cnt++; //两种退出状况,一种是到了链表结尾,另一种是找到值,我们返回p就可以 return cnt; } bool list_insert(int pos, int x) { //在某位置插入值 Node* p = list; int j = 0; while (p && j < pos- 1) { p = p->next; j++; } if (!p || j > pos - 1) return false; //如果输入位置不存在,返回false Node* s = new Node; s->date = x; //将新结点的date赋值 s->next = p->next; //尾插法逻辑 p->next = s; return true; //插入成功 } int list_len() { //遍历列表求其长度 int icount = 0; Node *node=list; while (node->next) { node = node->next; icount++; } return icount; } void list_print() { //遍历链表输出储存值 Node *node=list; node = node->next; while (node != NULL) { //当链表没有走到末尾 cout << node->date << " "; node = node->next; } cout << endl; } bool list_delete(int i) { //删除某元素 Node* p = list; int j = 0; while (p->next && j < i - 1) { p = p->next; j++; } if (!p->next || j > i - 1) return false; Node* q = p->next; p->next = q->next; delete q; return true; } int list_searchnode(int i) { //查询第i个结点的值 int j = 0; Node *node=list; while (j < i && node) { //停止条件是到达此节点或者到达链表末尾,在后面再检查是哪个原因停止下来的。 node = node->next; j++; } //cout << j << endl; if (!node || j > i) return -1; else return node->date; } }; I_can AK{ ios::sync_with_stdio(false); List ok; int n; cin>>n; ok.list_init(n); ok.list_print(); if(ok.list_insert(1,99)) cout<<"成功"<<endl; else cout<<"插入失败"<<endl; ok.list_print(); if(ok.list_delete(1)) cout<<"删除成功"<<endl; else cout<<"删除失败"<<endl; ok.list_print(); if(ok.list_find(5)) cout<<"第5这个值在链表中的位置"<<ok.list_find(5)+1<<endl; else cout<<"未查询到此值"<<endl; if(ok.list_searchnode(1)!=-1) cout<<ok.list_searchnode(1)<<endl; else cout<<"此节点不存在"<<endl; cout<<"此链表长度为:"<<ok.list_len()<<endl; ok.list_print(); return Accepted; }
数据结构算法学习 文章被收录于专栏
算法学习记录