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
| #include<stdio.h> #include<malloc.h> #include <stdlib.h> typedef struct Node { int data; struct Node * pNext; }NODE, *PNODE; PNODE create_list(void); void traverse_list(PNODE pHead); bool is_empty(PNODE pHead); int length_list(PNODE pHead); bool insert_list(PNODE pHead, int pos, int val); bool delete_list(PNODE pHead, int pos, int *pVal); void sort_list(PNODE pHead);
int main(void) { PNODE pHead = NULL; int val; pHead = create_list(); sort_list(pHead); if (delete_list(pHead, 4, &val)) { printf("succes! your delete is %d\n", val); } traverse_list(pHead); int len = length_list(pHead); printf("len = %d", len); return 0; }
PNODE create_list(void) { int len; int i; int val; PNODE pHead = (PNODE)malloc(sizeof(NODE)); if (NULL == pHead) { printf("分配失败"); exit(-1); } PNODE pTail = pHead; pTail->pNext = NULL; printf("输入链表节点个数:len=");\ scanf("%d", &len); for (i = 0; i < len; ++i) { printf("输入第%d个节点的值:", i+1); scanf("%d", &val); PNODE pNew = (PNODE)malloc(sizeof(NODE)); if (NULL == pNew) { printf("分配失败"); exit(-1); } pNew->data = val; pTail->pNext = pNew; pNew->pNext = NULL; pTail = pNew; } return pHead; }
void traverse_list(PNODE pHead) { PNODE p = pHead->pNext; while (NULL != p) { printf("%d ", p->data); p = p->pNext; } printf("\n"); return; }
bool is_empty(PNODE pHead) { if (NULL == pHead->pNext) { return true; } else { return false; } }
int length_list(PNODE pHead) { PNODE p = pHead->pNext; int len = 0; while (NULL != p) { ++len; p = p->pNext; } return len; }
void sort_list(PNODE pHead) { int i, j, t; int len = length_list(pHead); PNODE p, q; for (i = 0, p = pHead->pNext; i < len -1; ++i, p = p->pNext) { for (j = i + 1, q = p->pNext; j < len; ++j, q = q->pNext) { if (p->data > q->data) { t = p->data; p->data = q->data; q->data = t; } } } return; }
bool insert_list(PNODE pHead, int pos, int val) { int i = 0; PNODE p = pHead; while (NULL != p && i < pos-1) { p = p->pNext; ++i; } if (i>pos-1 NULL==p) { return false; } PNODE pNew = (PNODE)malloc(sizeof(NODE)); if (NULL == pNew) { printf("error of memary!"); exit(-1); } pNew->data = val; PNODE q = p->pNext; p->pNext = pNew; pNew->pNext = q; return true; }
bool delete_list(PNODE pHead, int pos, int *pVal) { int i = 0; PNODE p = pHead; while (NULL != p->pNext && i < pos-1) { p = p->pNext; ++i; } if (i > pos-1 NULL == p->pNext) { return false; } PNODE q = p->pNext; *pVal = q->data; p->pNext = p->pNext->pNext; free(q); q = NULL; return true; }
|