#include<bits/stdc++.h>
#include<iostream>
#include<stdlib.h>
#include<assert.h>
using namespace std;
typedef struct stlist {
int data;
stlist* next;
} stlnode;
stlnode* buynode(int x){//创造结点
stlnode *pos=(stlnode*)malloc(sizeof(stlnode*));
pos->data=x;
pos->next=NULL;
return pos;
}
void printlist(stlnode* phead) {
stlnode* cur=phead;
while(cur) {
cout<<cur->data;
cur=cur->next;
}
}
void pushback(stlnode** phead,int x) { //尾插
assert(phead);
stlnode* newnode=(stlnode*) malloc(sizeof(stlnode));
newnode->data=x;
newnode->next=NULL;
if(*phead==NULL) *phead=newnode;
else {
stlnode* tail=*phead;
while(tail->next) {
tail=tail->next;
}
tail->next=newnode;
}
}
void deletestlplist(stlnode **phead) { //尾删
assert(phead);
assert(*phead);
if((*phead)->next==NULL) {
delete(*phead);
*phead=NULL;
} else {
stlnode * tail=*phead;
while(tail->next->next) {
tail=tail->next;
}
delete(tail->next);
tail->next=NULL;
}
}
void headpush(stlnode** phead,int x) { //头插
assert(phead);
stlnode * newnode=(stlnode*)malloc(sizeof(stlnode));
newnode->data=x;
newnode->next=*phead;
*phead=newnode;
}
void insertnode(stlnode** phead,stlnode*pos,int x){//任意位置插入
stlnode*newnode=(stlnode*)malloc(sizeof(stlnode*));
if(*phead==pos){
newnode->next=*phead;
*phead=newnode;
}
else{
stlnode*prev=*phead;
while(prev->next!=pos){
prev=prev->next;
}
prev->next=newnode;
newnode->next=pos;
}
}
void headdelete(stlnode** phead) { //头删
assert(phead);
assert(*phead);
stlnode* cur=*phead;
*phead=(*phead)->next;
delete(cur);
cur=NULL;
}
void deletenode(stlnode** phead,stlnode* tmp) { //删除给定的结点
assert(phead);
assert(tmp);
if(*phead==tmp) {
stlnode * cur=*phead;
*phead=(*phead)->next;
delete(cur);
cur==NULL;
} else {
stlnode * p=*phead;
while(p->next!=tmp) {
p=p->next;
assert(p->next);
}
p->next=tmp->next;
delete(tmp);
tmp=NULL;
}
}
stlnode* findnode(stlnode* phead,int x) { //寻找结点
stlnode*cur=phead;
while(cur) {
if(cur->data==x) {
return cur;
}
cur=cur->next;
}
return NULL;
}
void changenode(stlnode** phead,int y,int x) { //更改某个结点
stlnode*cur=*phead;
for(int i=1; i<y; i++) {
cur=cur->next;
}
cur->data=x;
}
void listdestory(stlnode** phead){//链表销毁
assert(phead);
stlnode* cur=*phead;
stlnode* pos;
while(cur){
pos=cur->next;
delete(cur);
cur=pos;
}
*phead=NULL;
}
int main() {
stlnode* plist=NULL;
pushback(&plist,1);
pushback(&plist,2);
pushback(&plist,3);
pushback(&plist,4);
printlist(plist);
cout<<endl;
deletestlplist(&plist);
printlist(plist);
cout<<endl;
headdelete(&plist);
printlist(plist);
cout<<endl;
headpush(&plist,8);
printlist(plist);
cout<<endl;
changenode(&plist,2,6);
printlist(plist);
cout<<endl;
stlnode* pos=findnode(plist,6);
int i=1;
while(pos){
cout<<++i<<endl<<pos;
pos=findnode(pos->next,2);
}
}