数据结构学习第二天
21:31:04 2019-08-17
今天开始的时间有点晚
00:09:22 2019-08-18
又重新开始学 希望这次能够入门 每天开始学习数据结构的时间有点晚了 要调整一下
23:26:58 2019-08-20
补上了测试
单链表
List.h
1 #ifndef _LIST_H 2 #define _LIST_H 3 #define len sizeof(Node) 4 5 typedef struct Node* PtrToNode; 6 typedef PtrToNode List; 7 typedef PtrToNode Position; 8 struct Node 9 { 10 int Element; 11 Position Next; 12 }; 13 List MakeEmety(List L); 14 int IsEmpty(List L); 15 int IsLast(Position P, List L); 16 Position Find(int Element, List L); 17 void Delete(int Element, List L); 18 Position FindPrevious(int Element, List L); 19 void Insert(int Element, List L, Position P); 20 void DeleteList(List L); 21 Position Header(List L); 22 Position First(List L); 23 24 #endif // !_LIST_H
List.c
1 #include<malloc.h> 2 #include "List.h" 3 extern struct Node; 4 5 List MakeEmety(List L) 6 { 7 L = (List)malloc(len); 8 L->Element = 0; 9 L->Next = NULL; 10 return L; 11 } 12 13 int IsEmpty(List L) 14 { 15 return L->Next == NULL; 16 } 17 18 19 int IsLast(Position P, List L) 20 { 21 return P->Next == NULL; 22 } 23 24 Position Find(int Element, List L) 25 { 26 Position P = L->Next; 27 /*while (P!=NULL) 28 { 29 if (P->Element == Element) 30 return P; 31 else 32 P = P->Next; 33 } 34 return NULL;*/ 35 while (P!=NULL&&P->Element!=Element) 36 { 37 P = P->Next; 38 } 39 return P; 40 } 41 42 void Delete(int Element, List L) 43 { 44 Position P1, P2; 45 P1=P2= FindPrevious(Element,L); 46 P2 = P1->Next; 47 //P1->Next = P1->Next->Next; 48 P1->Next = P2->Next; 49 free(P2); 50 } 51 52 Position FindPrevious(int Element, List L) 53 { 54 Position P = L; 55 /*while (P ->Next!= NULL) 56 { 57 if (P->Next->Element == Element) 58 return P; 59 else 60 P = P->Next; 61 } 62 return NULL;*/ 63 while (P->Next!=NULL&&P->Next->Element!=Element) 64 { 65 P = P->Next; 66 } 67 return P; 68 } 69 70 void Insert(int Element, List L, Position P) 71 { 72 Position P1 = (Position)malloc(len); 73 P1->Element = Element; 74 Position PreP = FindPrevious(P->Element,L); 75 P1->Next = P; 76 PreP->Next = P1; 77 } 78 79 void DeleteList(List L) 80 { 81 Position P1, P2; 82 P1 = P2 = L; 83 while (P2!= NULL) 84 { 85 P2 = P1->Next; 86 free(P1); 87 P1 = P2; 88 } 89 } 90 91 Position Header(List L) 92 { 93 return L; 94 } 95 96 Position First(List L) 97 { 98 return L; 99 }
main.c
1 #include<stdio.h> 2 #include<malloc.h> 3 #include"List.h" 4 using namespace std; 5 int main() 6 { 7 List L=NULL; 8 L=MakeEmety(L); 9 printf("%10d %10d\n", IsEmpty(L),IsLast(L,L)); 10 Position P = (Position)malloc(len); 11 L->Next = P; 12 P->Element = 20; 13 P->Next = NULL; 14 printf("%10d %10d\n", P->Element, IsLast(P, L)); 15 Insert(25, L, P); 16 printf("%10d %10d\n", L->Next->Element, IsLast(L->Next, L)); 17 printf("%10d\n", Find(20, L)->Element); 18 Delete(20, L); 19 Delete(25, L); 20 printf("%10d\n", IsEmpty(L)); 21 DeleteList(L); 22 return 0; 23 }
运行结果