今晚上干了许久的链表
看见指针就头大的我真的是头皮发麻了一晚上
代码中写有注释,虽然不是太详细,但是了指针熟练的同学应该可以看懂
main函数中请自由发挥
#pragma GCC optimize(3,"Ofast","inline")
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <math.h>
#include <string>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <stdlib.h>
#define maxn 1000005
//#define true false
//#define false true
const int MaxN = 0x3f3f3f3f;
const int MinN = 0xc0c0c00c;
const double pi = acos(-1);
typedef long long ll;
ll mod;
using namespace std;
struct Node { //单链表储存结构
int date;
Node* next;
};
Node* list_creathead() { //单链表的初始化
Node* node = new Node; //生成新结点作为其头节点
node->date = 0;
node->next = NULL; //将头节点的next域置为空
return node;
}
void list_input(Node* node, int n) { //创建单链表 p是在链表中移动的,r是指向尾节点的
Node* r = node; //创建尾指针,指向头节点
for (int i = 0; i < n; i++) {
Node* p = new Node; //生成新结点
cin >> p->date;
p->next = NULL;
r->next = p;
r = p;
}
}
Node* list_find(Node* node, int x) { //查找某个值在链表中的位置
Node* p = node->next;
while (p && p->date != x) p = p->next; //两种退出状况,一种是到了链表结尾,另一种是找到值,我们返回p就可以
return p;
}
bool list_insert(Node* node, int i, int x) { //在某位置插入值
Node* p = node;
int j = 0;
while (p && j < i - 1) {
p = p->next;
j++;
}
if (!p || j > i - 1) return false; //如果输入位置不存在,返回false
Node* s = new Node;
s->date = x; //将新结点的date赋值
s->next = p->next; //尾插法逻辑
p->next = s;
return true; //插入成功
}
int list_len(Node* node) { //遍历列表求其长度
int icount = 0;
while (node->next) {
node = node->next;
icount++;
}
return icount;
}
void list_print(Node* node) { //遍历链表输出储存值
node = node->next;
while (node != NULL) { //当链表没有走到末尾
cout << node->date << " ";
node = node->next;
}
cout << endl;
}
bool list_delete(Node* node, int i) { //删除某元素
Node* p = node;
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(Node* node, int i) { //查询第i个结点的值
int j = 0;
while (j < i && node) { //停止条件是到达此节点或者到达链表末尾,在后面再检查是哪个原因停止下来的。
node = node->next;
j++;
}
cout << j << endl;
if (!node || j > i) return -1;
else return node->date;
}
int main()
{
return 0;
}