P74链表入门操作

    科技2022-07-13  133

    题目描述:

    代码实现

    #include<stdlib.h> #include<stdio.h> typedef char ElemType ; typedef struct LNode { ElemType data ; struct LNode *next; }LinkNode; void InitList (LinkNode*&L)//初始化 { L=(LinkNode*)malloc(sizeof(LinkNode)); L->next=NULL; } void DestroyList(LinkNode*&L)//销毁链表 { LinkNode*p,*pre ; pre=L; while (p!=NULL) { p=pre->next; free(pre ); pre=p; } free(pre);//用free(p)也可以 } bool ListEmpty(LinkNode*&L)//判断是否为空 { return(L->next!=NULL);//bool类型,返回真或假 根据需要判断的值判断为真假后输出 } int ListLength(LinkNode*&L)//输出链表长度 { int n=0; LinkNode * p; p=L; while (p->next!=NULL) { n++; p=p->next; } return (n);//注意此时需要带括号且此种有返回值,就是可以返回一个值,而且不需要定义变量 } void DispList(LinkNode*&L)//陈列出来所有元素 { LinkNode*p=L->next; while (p!=NULL) { printf("%c\n",p->data);//没有printf 咋么来输出? p=p->next; } } bool GetElem(LinkNode*&L,int i,ElemType &e)//查找第几个元素 { LinkNode*p=L; int n=0; if(i<0)return false; while (n<i&&L->next!=NULL) { n++; p=p->next; } if(p==NULL) { return false; } else { e=p->data; return true ; } } int LocateElem(LinkNode*&L,ElemType e)//根据元素找位置 { int i = 1 ; LinkNode*p=L->next; while (p!=NULL&&p->data!=e) { p=p->next; i++; } if(p==NULL) return (0); else { return (i); } } bool ListInsert(LinkNode*&L,int i,ElemType e)//插入元素 { LinkNode*p=L; LinkNode*s; int j=0; if(i<1) return false; while (p!=NULL&&j<i-1) { j++; p=p->next; } if(p==NULL) return false; else { s=(LinkNode*)malloc(sizeof(LinkNode)); s->data = e; s->next=p->next; p->next=s; return true; } } bool ListDelate(LinkNode*&L,int i,ElemType e)//删除元素 { LinkNode *p=L; LinkNode*q ; int j=0; if(i<1) return false; while (p!=NULL&&j<i-1) { j++; p=p->next; } if (p==NULL) return false ; else { q=p->next; if(q==NULL) { return false; } if(q==NULL) return false ; else { e=q->data; p->next=q->next; free(q); return true ; } } } int main () { int i ; LinkNode *L; ElemType e; InitList(L); printf("1.已初始化\n"); printf("2.依次插入元素:a,b,c,d,e\n"); ListInsert(L,1,'a'); ListInsert(L,2,'b'); ListInsert(L,3,'c'); ListInsert(L,4,'d'); ListInsert(L,5,'e'); printf("3.输出单链表:\n"); DispList(L); printf("4.输出单链表长度:\n"); ListLength(L); printf("%d\n", ListLength(L)); printf("5.判断表是否为空(若为空返回0)\n"); ListEmpty(L); printf("%d\n",ListEmpty(L)); printf("6.输出第3个元素:\n"); GetElem(L,3,e); printf("%c\n",e); printf("7.输出元素a的位置:\n"); LocateElem(L,'a'); printf("%d\n",LocateElem(L,'a')); printf("8.在第四个位置插上元素f\n已插入\n"); ListInsert(L,4,'f'); printf("9.输出单链表:\n"); DispList(L); printf("10.删除单链表第3个元素\n已删除\n"); ListDelate(L,3,e); printf("11.输出单链表\n");//只有这一个 函数内部有输出函数 DispList(L); printf("12.释放单链表\n已释放\n"); DestroyList(L); return 0 ; }
    Processed: 0.010, SQL: 8