#include<iostream>
using namespace std;
struct LinkNode{
int data;
LinkNode *link;
};
typedef LinkNode* NodePtr;
//头部插入
void Insert(NodePtr &head, int data){
NodePtr temp = new LinkNode;
temp -> link = head;
temp -> data = data;
head = temp;
}
//迭代输出
void Iter(NodePtr head){
for(NodePtr here = head; here != 0; here = here -> link){
cout << here -> data << endl;
}
}
//搜索 data 返回指针
NodePtr Search(NodePtr head, int target){
for(NodePtr here = head; here != 0; here = here -> link){
if(here -> data == target){
return here;
}
}
}
//后插入
void AfterInit(NodePtr head, int target, int value){
NodePtr afterMe = Search(head, target);
NodePtr newNode = new LinkNode;
newNode -> link = afterMe -> link;
newNode -> data = value;
afterMe -> link = newNode;
}
//前插入
void BeforeInit(NodePtr head, int target, int value){
NodePtr beforeMe = Search(head, target); //位于新元素之后
NodePtr newNode = new LinkNode;
newNode -> data = value;
for(NodePtr here = head; here != 0; here = here -> link){
if(here -> link == beforeMe){
//此时的 here 就是新元素之前的元素
here -> link = newNode;
newNode -> link = beforeMe;
break;
}
}
}
int main(){
NodePtr head;
head = new LinkNode;
head -> data = 13;
head -> link = 0;
cout << head -> data << endl << "---" << endl;
Insert(head, 11);
Insert(head, 10);
Insert(head, 9);
Insert(head, 8);
Iter(head);
cout << "---" << endl;
BeforeInit(head, 13, 12);
Iter(head);
return 0;
}