#include<iostream>
#include<stdexcept>
using namespace std;
template<typename T>
struct node {
node *next;
T val;
node(T x):val(x),next(NULL){ }
};
//头插法建立单链表
template<typename T>
node<T>* create_head(T a[],size_t n){
node<T> *head,*p;
head=NULL;
while(n--){ss
p=new node<T>(a[n]);
p->next=head;
head=p;
}
return head;
}
//尾插法建立单链表
template<typename T>
node<T>* create_tail(T a[],size_t n){
node<T> *head,*tail,*p;
head=NULL;
for(size_t i=0;i<n;++i){
p=new node<T>(a[i]);
p->next=NULL;
if(i==0){
head=tail=p;
}else{
tail->next=p;
tail=p;
}
}
return head;
}
//输出单链表
template<typename T>
void output(node<T> *head){
while(head){
cout<<head->val<<" ";
head=head->next;
}
}
//在单链表中第m个节点之后,插入一个新节点
template<typename T>
node<T>* inse(node<T>* head,size_t m,T x){
node<T> *p,*pre;
if(m==0){
p=new node<T>(x);
p->next=head;
head=p;
return head;
}else{
pre=head;
m=m-1;
while(m-- && pre){
pre=pre->next;
}
if(!pre)
throw range_error("the mth node is not exist!");
p=new node<T>(x);
p->next=pre->next;
pre->next=p;
return head;
}
}
//删除单链表中值大于x,小于y的节点
template<typename T>
node<T>* del(node<T>* head,T x,T y){
node<T> *p,*pre;
p=pre=head;
while(p){
if(p->val>x && p->val<y){
if(p==head){
head=head->next;
delete p;
p=pre=head;
}else{
pre->next=p->next;
delete p;
p=pre->next;
}
}else{
if(pre==p)
p=p->next;
else{
pre=pre->next;
p=p->next;
}
}
}
return head;
}
//销毁单链表,回收堆上的空间
template<typename T>
void destroy(node<T>* head){
node<T> *p;
while(head){
p=head;
head=head->next;
delete p;
}
}
int main(){
int a[10]={3,5,2,3,6,7,4,9,1,6};
node<int> *head=create_head(a,10);
output(head);
cout<<endl;
head=inse(head,3,7);
output(head);
cout<<endl;
head=inse(head,0,6);
output(head);
cout<<endl;
head=del(head,2,5);
output(head);
cout<<endl;
head=inse(head,-3,6);
output(head);
cout<<endl;
head=del(head,5,7);
output(head);
cout<<endl;
destroy(head);
}
单链表操作
最新推荐文章于 2022-09-24 23:41:50 发布