//单链表 typedef struct LNode{ int data; struct LNode* next; }LNode; LNode L; //初始化 void InitList(LNode *&L){ L = (LNode*)malloc(sizeof(LNode)); L -> next = NULL; } //判断线性表是否为空 bool ListEmpty(LNode *L){ return L -> next == NULL; } //尾插法 void CreatelistR(LNode *&L,int a[],int n){ LNode *s,*r; //s指向新申请的结点 r = L; for(int i = 0 ; i < n ; i++){ s = (LNode*)malloc(sizeof(LNode)); s -> data = a[i]; r -> next = s; r = s; } r -> next = NULL; } //头插法 void CreateListF(LNode *&L,int a[],int n){ LNode *s; for(int i = 0 ; i < n ; i++){ s = (LNode*)malloc(sizeof(LNode)); s -> data = a[i]; s -> next = L -> next; L -> next = s; } } //插入 bool InsertList(LNode *&L,int i,int x){ int n = 0; LNode *r = L , *s; if(i < 0)return false; while(n < i-1 && r != NULL){ r = r -> next; n++; } if(r == NULL) //r = i-1; return false; else{ s = (LNode*)malloc(sizeof(LNode)); s -> data = x; s -> next = r -> next; r -> next = s; return true; } } //删除 bool DeleteList(LNode *&L,int i,int &e){ int n = 0; LNode *r = L , *q; if(i <= 0)return false; while(n < i-1 && r->next != NULL){ r = r -> next; n++; } if(r == NULL) return false; else{ q = r -> next; if(q == NULL) return false; e = q -> data; r -> next = q -> next; free(q); return true; } } //按元素值查找 int FindElem(LNode *L , int e){ int n = 1; LNode *r = L -> next; while(r!=NULL && r -> data != e){ r = r -> next; n++; } if(r == NULL) return 0; else return n; } //按位置查找 bool GetElem(LNode* L, int i, int &e){ int n = 0; LNode * r =L; if(ListEmpty(L)) cout<<"空表"endl; if(i <= 0) return false; while(r != NULL && n < i){ n++; r = r -> next; } if(r == NULL) return false; else{ e = r -> data; return true; } } //求链表表的长度 int ListLength(LNode *L){ int n = 0; LNode *r =L; while(r -> next != NULL){ n++; r = r -> next; } return n; }