#include<iostream>#include<cstdio>#include<cstdlib>using namespace std;typedef struct node{struct node *next;int data;}*List;
void initList(List *L){*L=(node*)malloc(sizeof(node));(*L)->next=NULL;}//创建单链表 前插法void FrontCreateList(List L,int n){node *p;// L=(node*)malloc(sizeof(node));//L->next=NULL;for(int i=0;i<n;i++){p=(node*)malloc(sizeof(node));cin>>p->data;p->next=L->next;L->next=p;}}//尾插法创建单链表void rearCreateList(List L,int n){node *r,*s;// L=(node *)malloc(sizeof(node));动态指针指向链表的表当前表尾,r=L;for(int i=0;i<n;i++){s=(node *)malloc(sizeof(node));cin>>s->data;r->next=s;r=s;}r->next=NULL;}//插入链表元素void insertList(List L,int i,int *e){
node *s,*p;p=L->next;int j=1;while(j<i&&p!=NULL){p=p->next;j++;}s=(node *)malloc(sizeof(node));s->data=*e;s->next=p->next;p->next=s;
}//删除链表元素void DeleteList(List L,int i){node *p,*r;p=L->next;int j=1;while(j<i){p=p->next;j++;}r=p->next;p->next=r->next;free(r);}//得到链表长度int GetListlengthe(List L){node *s;s=L->next;int j=0;while(s){j++;s=s->next;}return j;}//判断链表是否为空bool Listisempty(List L){if(L->next==NULL){return true;}else return false;}//查询链表元素void SearchlistElement(List L,int k){node *s;s=L->next;while(s!=NULL){if(s->data==k){cout<<"已找到"<<endl;break;}s=s->next;}
if(s==NULL) cout<<"未找到";}//打印链表元素void PrintList(List L){node *p;p=L->next;while(p){cout<<p->data<<" ";p=p->next;}cout<<endl;}int main(){List L;initList(&L);int n;cin>>n;rearCreateList(L,n);
PrintList(L);FrontCreateList(L,n);PrintList(L);cout<<GetListlengthe(L);*/cout<<GetListlengthe(L)<<endl;int e=5;if(Listisempty(L))cout<<"yes";else cout<<"no";SearchlistElement(L,3);int e=10;insertList(L,2,&e);PrintList(L);*/DeleteList(L,3);PrintList(L);return 0;}
单链表的基本操作
最新推荐文章于 2021-12-24 21:22:58 发布