单链表
来源:互联网 发布:origin8怎么数据拟合 编辑:程序博客网 时间:2024/06/07 16:29
单链表练习记录
#include <stdio.h> #include<stdlib.h>//相关操作:创建,清空,查空,插入,查询,排序typedef int ElemType;typedef struct Node{ ElemType data; struct Node *next;}Node, *LinkedList;LinkedList InitList(void) //主要要分配空间,{ Node *L; // 头指针 L = (Node *)malloc(sizeof(Node)); if(L == NULL) { printf("apply for memory failed!\n"); } L->data = 0; L->next = NULL; return L;}bool ListEmpty(LinkedList L){ if (L->next == NULL) return true; else return false;}void ClearList(LinkedList L){ LinkedList head = L; while (L->next != NULL) { LinkedList L_next = L; L = L_next->next; free(L_next); } free(L); head->data = 0; head->next = NULL;}void ListInsert(LinkedList L, ElemType element){ L->data += 1; while (L->next != NULL) L = L->next; L->next = (Node *)malloc(sizeof(Node)); L = L->next; L->data = element; L->next = NULL;}void GetElem(LinkedList L, int i, ElemType& e){ if (L->data < i) { printf("out of length\n"); } else { while (i) { L = L->next; i--; } e = L->data; }}int LocateElem(LinkedList L, ElemType e){ int i = 0; while (L->next != NULL) { L = L->next; i++; if (L->data == e) { return i; } }}void ListDelete(LinkedList L, ElemType e){ while (L->next != NULL) { LinkedList L_n = L->next; if (L_n->data == e) { L->next = L_n->next; free(L_n); printf("Delete the element!\n"); return; } else { L = L_n; } } printf("The element is not in the list!\n");}int main(int argc, char **argv){ LinkedList L1; ElemType e1; int location; int result; L1 = InitList(); result = ListEmpty(L1); ListInsert(L1, 1); ListInsert(L1, 3); ListInsert(L1, 4); ListInsert(L1, 5); GetElem(L1, 2, e1); location = LocateElem(L1, 3); ListDelete(L1,3); ClearList(L1); return 0;}
0 0