1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <stdio.h> #include <stdlib.h>
#define TRUE 1 #define FALSE 0
typedef struct Node //定义一个结点的数据结构 { int data; struct Node* next; } Node;
Node* initList() { Node* list = (Node*)malloc(sizeof(Node)); list ->data = 0; list ->next = NULL; return list;
}
void headInsert(Node* list, int data) { Node* node = (Node*)malloc(sizeof(Node)); node -> data = data; node -> next = list -> next; list -> next = node; list -> data++; }
void tailInsert(Node* L, int data) { Node* node = L; for(int i = 0; i < L -> data; i++) { node = node->next; } Node* n = (Node*)malloc(sizeof(Node)); n -> data = data; n -> next = NULL; node -> next = n; L -> data ++; }
void delete(Node* L, int data) { Node* preNode = L; Node* node = L -> next; while(node) { if(node -> data == data) { preNode -> next = node -> next; free(node); L -> data--; return TRUE; } preNode = node; node = node -> next; } return FALSE;
}
void printList(Node* L) { Node* node = L -> next; while(node) { printf("node = %d \n",node -> data); node = node -> next; }
}
int main() { printf("Hello world!\n"); Node* list = initList(); headInsert(list,1); headInsert(list,2); headInsert(list,3); headInsert(list,4); headInsert(list,5); tailInsert(list,6); tailInsert(list,7); tailInsert(list,8); tailInsert(list,9); tailInsert(list,10); printList(list); delete(list,9); printList(list); return 0; }
|