#include <bits/stdc++.h>
#define P pair<int,int>
using namespace std;
typedef long long LL;
typedef struct LNode{
int data;
struct LNode *nxt;
}LNode,*LinkList;
bool Linklist_init(LinkList &root){
root = new LNode; ///分配头结点,指针域为空,下一个结点才是第一个结点
root->nxt = NULL;
return true;
}
/**
查找链表中第k个元素(k下标从1开始)
*/
int Find_by_location(LinkList root,int k){
LinkList now = root->nxt;
if(!k) return -1;
int cnt = 1;
while(now && cnt < k){
now = now->nxt,cnt++;
}
if(!now) return -1;///第k个元素不存在
return now->data;
}
int Find_by_value(LinkList root,int value){
LinkList now = root->nxt;
while(now && now->data != value) now = now->nxt;
if(now) return 1;///找到了
return -1;///找不到
}
/**
头插法
*/
bool Insert(LinkList &root,int value){
LinkList now = new LNode;
now->data = value;
now->nxt = root->nxt;
root->nxt = now;
return true;
}
/**
在第pos - 1 和 第pos个元素之间插入数据
*/
bool Insert_by_location(LinkList root,int pos,int value){
if(!pos) return false;
int cnt = 0;
while(root && cnt < pos -1){
cnt++,root = root->nxt;
}
if(!root) return false;
LinkList now = new LNode;
now->data = value;
now->nxt = root->nxt;
root->nxt = now;
return true;
}
/**
删除第pos个元素
*/
bool Delete_by_location(LinkList root,int pos){
if(!pos) return false;
int cnt = 0;
while(cnt < pos - 1) cnt++,root = root->nxt;
if(!root) return false;
LinkList tmp = root->nxt;
root->nxt = tmp->nxt;
delete tmp;
tmp = NULL;
return true;
}
void rep_print(LinkList root){
root = root->nxt;
for(;root;root = root->nxt) printf("%d ",root->data);
printf("\n");
}
int main(void)
{
LinkList root;
Linklist_init(root);
for(int i = 1;i <= 10;i++) Insert(root,i);
rep_print(root);
Insert_by_location(root,3,15);
Insert_by_location(root,4,16);
rep_print(root);
Delete_by_location(root,5);
rep_print(root);
return 0;
}