带头结点的
#include<stdio.h> #include<string.h> #include<string> #include<cmath> #include<algorithm> #include<iostream> using namespace std; #define OK 1 #define ERROR 0 typedef int status; typedef struct LNODE { int data; struct LNODE *next; } LNode,*Linklist; status initLinset(Linklist &head) { head=(Linklist)malloc(sizeof(LNODE)); if(!head)return ERROR; head->next=NULL; return OK; } status insertList(Linklist &L,int i,int e) { int j=0,k; Linklist p,q; p=L; if(j>i-1)return ERROR; while(p&&j<i-1) { j++; p=p->next; } if(p!=NULL) { q=(Linklist)malloc(sizeof(LNODE)); if(q!=NULL) { q->data=e; q->next=p->next; p->next=q; return OK; } else return ERROR; } else return ERROR; } status deleteList(Linklist &L,int i) { int j=0,k; Linklist p,q; p=L; if(j>i-1)return ERROR; while(p&&j<i-1) { j++; p=p->next; } if(p!=NULL) { q=p->next; p->next=q->next; free(q); return OK; } else return ERROR; } status updataList(Linklist &L,int i,int e) { int j=0,k; Linklist p,q; p=L; if(j>i-1)return ERROR; while(p&&j<i) { j++; p=p->next; } if(p!=NULL) { p->data=e; return OK; } else return ERROR; } int getElem(Linklist L,int i) { int j=0,k; Linklist p,q; p=L; if(j>i-1)return ERROR; while(p&&j<i) { j++; p=p->next; } if(!p)return -1; else return p->data; } int query(Linklist L,int e) { int j=0,k; Linklist p,q; p=L->next; while(p) { j++; if(p->data==e)return j; else p=p->next; } return -1; } void traverse(Linklist L) { Linklist p,q; p=L->next; while(p) { printf("%d ",p->data); p=p->next; } printf(" "); } int getlength(Linklist L) { Linklist p,q; int j=0; p=L->next; while(p) { j++; p=p->next; } return j; } int main() { int i,j,k; Linklist head; initLinset(head); for(i=1; i<=10; i++) insertList(head,i,i); traverse(head); insertList(head,2,100); traverse(head); insertList(head,1,99); traverse(head); insertList(head,5,98); traverse(head); deleteList(head,1); traverse(head); deleteList(head,9); traverse(head); updataList(head,4,55); updataList(head,1,22); traverse(head); printf("%d %d %d ",getElem(head,3),getlength(head),query(head,33)); return 0; }