diff options
Diffstat (limited to 'c/dataStructure/线性表/线性链表/nhlist.c')
-rwxr-xr-x | c/dataStructure/线性表/线性链表/nhlist.c | 181 |
1 files changed, 181 insertions, 0 deletions
diff --git a/c/dataStructure/线性表/线性链表/nhlist.c b/c/dataStructure/线性表/线性链表/nhlist.c new file mode 100755 index 0000000..d37248d --- /dev/null +++ b/c/dataStructure/线性表/线性链表/nhlist.c @@ -0,0 +1,181 @@ +/* Function declaration -- Linked list without head pointer */ + +#include "list.h" + +void InitList(List * L) +{ + *L = NULL; +} + +void DestroyList(List * L) +{ + List tmp; + + while (*L) + { + tmp = (*L)->next; + free(*L); + *L = tmp; + } +} + +bool AddElem(List * L, ElemType e) +{ + List scan = *L; + + List new = (LNode *) malloc (sizeof(LNode)); + + if (!new) + { + fprintf(stderr,"Failed Adding element\n"); + return false; + } + + new->data = e; + new->next = NULL; + + if (!*L) + *L = new; + else + { + while (scan->next) + scan = scan->next; + scan->next = new; + } + + return true; +} + +bool ListEmpty (List * L) +{ + if (!*L) + return true; + return false; +} + +int ListLength (List * L) +{ + List tmp = *L; + int count = 0; + while (tmp) + { + tmp = tmp->next; + count++; + } + + return count; +} + +ElemType GetElem (List * L, int i) +{ + int n = ListLength(L); + if (i > n) + { + fprintf(stderr,"Position error, Please restricted between 0 and %d",n); + return EOF; + } + List tmp = *L; + + for (int j = 0; j < i; j++) + tmp = tmp->next; + + if (tmp) + return tmp->data; + return 0; +} + +void TraverseList (List * L) +{ + List tmp = *L; + + while (tmp) + { + printf("%7d",tmp->data); + tmp = tmp->next; + } + putchar('\n'); +} + +bool InsertElem (List * L, ElemType e, int i) +{ + bool flag = false; + List tmp = *L; + List new = (LNode *) malloc (sizeof(LNode)); + + int n = ListLength(&tmp); + + if (!new) + { + fprintf(stderr,"Failed to create new node!\n"); + return flag; + } + + new->data = e; + + if (i < 1) + fprintf(stderr,"Invalid position!\n"); + + else if (i == 1) + { + new->next = tmp; + *L = new; + flag = true; + } + + else + { + for (int j = 2; j < i; j++) + if (tmp->next) + tmp = tmp->next; + else + break; + + if (i > n) + printf("List length is %d, append element to last!\n",n); + + new->next = tmp->next; + tmp->next = new; + flag = true; + } + return flag; +} + +bool DeleteElem (List * L, int i) +{ + List t1 = *L; + List t2; + bool flag = false; + int n = ListLength(&t1); + + if (i < 1) + fprintf(stderr, "Position error!\n"); + + else if (i == 1) + { + t2 = t1; + *L = t1->next; + free(t2); + flag = true; + } + + else if (i <= n) + { + for (int j = 2; j < i; j++) + if (t1->next) + t1 = t1->next; + else + break; + + if (t1->next) + { + t2 = t1->next; + t1->next = t2->next; + free(t2); + flag = true; + } + } + + else + printf("No element at position %d\n",i); + return flag; +}
\ No newline at end of file |