#include <stdio.h> #include <stdlib.h> #define ElementType int typedef struct Node *List; typedef struct Node{ ElementType Data; List Next; }; int Length(List PtrL); List FindKth(int K,List PtrL); List Find(ElementType X,List PtrL); bool Insert(ElementType X,int i, List &PtrL); List Delete(int i,List &PtrL); void InitList(List PtrL){ PtrL= (List)malloc(sizeof(struct Node)); PtrL->Next=NULL; } void printL(List PtrL){ printf("-------------------------------------------------------------------\n"); List TmpList = PtrL; while(TmpList){ printf("%d\n",TmpList->Data); TmpList = TmpList->Next; } } int main(){ List PtrL; InitList(PtrL); Insert(10,1,PtrL); printL(PtrL); Insert(20,2,PtrL); printL(PtrL); for(int i = 1;i<10;i++) Insert(i,i,PtrL); printL(PtrL); for(int i = 1;i<5;i++) Delete(i,PtrL); Delete(5,PtrL); printL(PtrL); return 0; } int Length(List PtrL){ List TmpPtrL = PtrL; int i = 0; while(TmpPtrL){ TmpPtrL = TmpPtrL->Next; i++; } return i; } List FindKth( int K, List PtrL ) { List p = PtrL; int i = 1; while (p !=NULL && i < K ) { p = p->Next; i++; } if ( i == K ) return p; /* 找到第K个,返回指针 */ else return NULL; /* 否则返回空 */ } List Find(ElementType X,List L){ List TmpList = L; while(TmpList->Data!=X&&TmpList) TmpList = TmpList->Next; return TmpList;//不管是不是空,就是这一个 } bool Insert(ElementType X,int i, List &PtrL){ //如果插入节点到头部 List s,p; if(i==1){ s = (List)malloc(sizeof(struct Node)); s->Data=X; s->Next=PtrL; PtrL=s; //printf("%d",PtrL->Data); return true; } p = FindKth(i-1,PtrL); if(p==NULL){ printf("插入位置不合适\n"); return false; }else{ s = (List)malloc(sizeof(struct Node)); s->Data=X; s->Next=p->Next; p->Next=s; return true; } } List Delete(int i,List &PtrL){ //如果删除头结点 List s,p; if(i==1){ s = PtrL; PtrL = PtrL->Next; free(s); return PtrL; } p = FindKth(i-1,PtrL); if(p==NULL){ printf("第i-1个节点不存在\n"); return NULL; }else if(p->Next==NULL){ printf("第i个节点不存在\n"); return NULL; }else{ s = p->Next; p->Next=s->Next; free(s); return PtrL; } }
时间: 2024-10-25 16:33:27