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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
| #include "stdio.h" #include "malloc.h" #include<windows.h>
typedef struct LNode { int data; LNode* next; }LNode,*LinkList;
LinkList init() { LinkList L; L = (LNode*)malloc(sizeof(LNode)); L->next = NULL; return L; }
void insert1(LinkList L,int value) { LinkList p = L; LNode* q = (LNode*)malloc(sizeof(LNode)); if (!q) { printf("分配内存失败"); return; } q->next = p->next; q->data = value; L->next = q; }
void insert2(LinkList L, int value) { LinkList p = L; while (p->next != NULL) { p = p->next; }
LNode* q = (LNode*)malloc(sizeof(LNode)); if (!q) { printf("分配内存失败"); return; } q->data = value; q->next = NULL; p->next = q; }
int del(LinkList L, int index) { LinkList p = L; p = p->next; int i = 0; while (p!=NULL && i!=index-1) { p = p->next; i++; } if (!p || i!=index-1) { printf("指定索引的节点不存在"); exit(0); } LNode* q = p->next; int value = q->data; p->next = q->next; free(q); return value; }
void modify(LinkList L, int index, int value) { LinkList p = L; p = p->next; int i = 0; while (p != NULL && i != index) { p = p->next; i++; } if (!p || i != index) { printf("指定索引的节点不存在"); exit(0); }
p->data = value;
}
int select(LinkList L, int index) { LinkList p = L; p = p->next; int i = 0; while (p != NULL && i != index) { p = p->next; i++; } if (!p || i != index) { printf("指定索引的节点不存在"); exit(0); }
return p->data; }
void print(LinkList L) { LinkList p = L; p = p->next; while (p!=NULL) { printf("%d", p->data); p = p->next; } printf("\n"); }
int main() { LinkList L = init(); print(L);
for (int i = 0; i < 2; i++) { insert1(L, i); } print(L);
for (int i = 0; i < 3; i++) { insert2(L, i); } print(L);
int del_index = 2; int del_value = del(L, del_index); printf("被删除的值为:%d\n", del_value); print(L);
int modify_index = 1; int modify_value = 9; modify(L, modify_index, modify_value); print(L); int select_index = 1; int select_value = select(L,select_index); printf("查询到的第%d个节点的值为:%d\n",select_index+1, select_value); print(L);
return 0; }
|