建立单链表的两种方法:头插法(结果倒序)和尾插法(结果正序)
头插法:建立头结点,👉由头依次插入数据,由于要遍历每一个插入的数据,故时间复杂度为O(n)
核心代码:void CreateListF(LinkNode*& L, ElemType a[], int n) { LinkNode* s; L = (LinkNode*)malloc(sizeof(LinkNode)); L->next = NULL; for (int i = 0; i < n; ++i) { s = (LinkNode*)malloc(sizeof(LinkNode)); s->data = a[i]; s->next = L->next; L->next = s; } }
尾插法:建立头结点,👉在前结点后依次插入数据,由于要遍历每一个插入的数据,故时间复杂度也为O(n)
核心代码:void CreateListF(LinkNode*& L, ElemType a[], int n) { LinkNode* r ,*s; L = (LinkNode*)malloc(sizeof(LinkNode)); L->next = NULL; r = L; for (int i = 0; i < n; ++i) { s = (LinkNode*)malloc(sizeof(LinkNode)); s->data = a[i]; r->next = s; r = s; } r->next = NULL; }