刚刚开始学数据结构随便写写
#include <iostream>
using namespace std;
//伟大的雨辰同志友情赞助^_^
//创建于2021.3.11 未完待续O(∩_∩)O哈哈~
typedef int element_type;
typedef struct linkednode{ //链表定义
element_type data;
linkednode *next;
}snode,*ptr;
void initLink(ptr &h){ //初始化单向加头链表
h = new snode;
if(h==NULL) //理论上每次申请空间后都要判断 偷懒起见就写一次
exit(0);
h->next=NULL;
}
void headInsert(ptr p){//头插法 每次在头结点后面插入
ptr t = new snode;
cin >> t->data;
t->next = p->next;
p->next = t;
}
void tailInsert(ptr p){ // 尾插法
ptr t = new snode;
cin >> t->data;
while(p->next){ //定位
p=p->next;
}
t->next = p->next;
p->next = t;
}
void ascInsert(ptr p) {//升序插入链表
ptr t = new snode;
cin >> t->data;
ptr last = p; //last 是p的前驱
p=p->next;
while( p&& t->data > p->data){ //定位 最后p指向NULL(1.还没有首元结点 2.t->data是最大值) 或者 p为>=t的节点 注:一定要先判断p是否是空指针
last = p;
p = p->next;
}
t->next = last->next;
last->next = t;
}
void descInsert(ptr p){//降序插入链表
//升序插入while循环条件改成p&& t->data < p->data 即可
}
bool addLink(ptr p,int x){//在链表的第x个位置添加结点
cout << "请输入添加结点的值\n";
ptr t = new snode;
cin >> t->data;
if(x<1){
cout<<"错误代码03"<<endl;
return false;
}
for(int cnt=0;p&&cnt<x-1;cnt++){ //定位
p=p->next;
}
if(p){
t->next = p->next;
p->next = t;
return true;
}else{
cout<<"错误代码04"<<endl;
return false;
}
}
bool delLink(ptr p,int x){ //删除第x个结点
ptr del;
if(x<1){
cout <<"错误代码05\n";
return false;
}
for(int cnt=0;p && cnt<x-1; cnt++) //定位
p=p->next;
if(p){
del = p->next;
p->next = p->next->next;
delete del;
return true;
}else {
cout<<"错误代码06\n";
return false;
}
}
bool correctLink(ptr p, int x){ //更改第x个结点的值
if(x<1){
cout<<"错误代码07\n";
return false;
}
for(int cnt=0; p&&cnt<x;cnt++) //定位第x个结点
p=p->next;
if(p){
cout << "请输入变更值\n";
cin >>p->data;
return true;
}else{
cout <<"错误代码08\n";
return false;
}
}
ptr searchLinkValue(ptr p,element_type x){ //按值查找第一个结点,并返回该节点的地址
p = p->next;
int cnt =1; //计数器
while(p){
if(p->data == x){
cout << p->data<<"是第"<<cnt<<"个结点"<<endl;
return p;
}
cnt++;
p = p->next;
}
cout << "未查到"<<x<<endl;
return NULL;
}
ptr searchLinkNum(ptr p, int x){ //按序号查找结点,并返回该节点地址
if(x<1){
cout << "错误代码01"<<endl;
return NULL;
}
for(int cnt=0; p&& cnt<x; cnt++){
p=p->next;
}
if(p){
cout << "第"<<x<<"个结点的值为:"<<p->data<<endl;
return p;
}else{ //p==NULL 越界
cout << "错误代码02"<<endl;
return NULL;
}
}
void printLink(ptr p){ //遍历链表
p = p->next;
while(p){
cout <<p->data<<'\t';
p=p->next;
}
cout <<'\n';
}
int main(){
int n;
ptr head;
initLink(head);
cin >>n;
for(int i=0; i<n; i++){
// headInsert(head);
tailInsert(head);
}
printLink(head);
// cout<<"请输入删除结点位置\n";
// cin >>n;
// delLink(head,n);
// printLink(head);
cout <<"请输入更改数值结点位置\n";
cin >>n;
correctLink(head,n);
printLink(head);
// cout<<"请输入添加结点位置\n";
// cin >> n;
// addLink(head,n);
// printLink(head);
// searchLinkValue(head,999);
// searchLinkNum(head,3);
return 0;
}