#include<iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
};
ListNode* greate(){
ListNode *head=new ListNode;
head=NULL;
ListNode *p=head;
cout<<"please enter student number:";
int n;
cin>>n;
for(int i=0;i<n;i++){
p=new ListNode;
p->val=i;
p->next=head;
head=p;
}
return head;
}
void prin(ListNode* head){
ListNode *p=head;
cout<<endl;
while(p!=NULL){
cout<<p->val<<endl;
p=p->next;
}
}
void insert(ListNode* head,int n){
ListNode *sert,*nex,*p;
sert=new ListNode;
sert->val=2;
p=head;
while(p->val!=n)
p=p->next; //插入到n后面
nex=p->next;
p->next=sert;
sert->next=nex;
}
void deleter(ListNode* head,int n){
ListNode *out=new ListNode;
ListNode *p;
p=head;
while(p->val!=n){
out=p;
p=p->next;
}
out->next=p->next;
}
int main(){
ListNode *h1;
h1=greate();
prin(h1);
insert(h1,1);
prin(h1);
deleter(h1,0);
prin(h1);
return 0;
}
另一个写法:
#include<iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int num=0;
ListNode* greate(){
ListNode *head;
ListNode *p;
cout<<"please enter student number:";
int n;
cin>>n;
for(int i=0;i<n;i++){
if(num==0){
head = new ListNode(i);
}else{
p=new ListNode(i);
p->next=head;
head=p;
}
num++;
}
return head;
}
void prin(ListNode* head){
ListNode *p=head;
cout<<endl;
while(p!=NULL){
cout<<p->val<<endl;
p=p->next;
}
}
void insert(ListNode* head,int n){
ListNode *sert,*nex,*p;
sert=new ListNode(2);
p=head;
while(p->val!=n)
p=p->next; //插入到n后面
nex=p->next;
p->next=sert;
sert->next=nex;
}
void deleter(ListNode* head,int n){
ListNode *out=new ListNode(NULL);
ListNode *p;
p=head;
while(p->val!=n){
out=p;
p=p->next;
}
out->next=p->next;
}
int main(){
ListNode *h1;
h1=greate();
prin(h1);
insert(h1,1);
prin(h1);
deleter(h1,0);
prin(h1);
return 0;
}
可算把这东西整明白一点了!