继续复习链表知识点,本章包含单链表的增加,删除,判断是否为空,和链表长度,以及链表的排序 几个知识点
1.链表的判断是否为空
//1.判断链表是否为空bool isempty_list(PNODE pHead) { return pHead->pNext == NULL;}
2. 计算链表的长度
//2.链表长度int length_list(PNODE pHead) { PNODE pFirst = pHead->pNext;//获取头结点 int num = 0; while (pFirst != NULL) { num++; pFirst = pFirst->pNext; } return num;}
3. 在制定位置增加节点
//指索引位置插入节点bool insert_list(PNODE pHead, int pos, int data) { PNODE p = pHead;//头结点 int i = 0; while (p != NULL&&i <= pos) { p = p->pNext; i++; } //pos 是索引位置,循环i不能>pos+1 if (p == NULL || i > (pos + 1)) { return false; } PNODE pNew = (PNODE)malloc(sizeof(PNODE)); if (NULL == pNew) { printf("内存分配失败"); exit(-1); } pNew->data = data; pNew->pNext = p->pNext; int pVal = p->data; p->pNext = pNew; return true;}
4. 在指定位置删除节点
bool delete_list(PNODE pHead, int pos) { PNODE p = pHead->pNext; int i = 0; //这样循环为了获取pos 前面一个节点 while (NULL != p&&i < pos - 1) { p = p->pNext; i++; } if (NULL == p || i > pos - 1) { return false; } PNODE q = p->pNext; p->pNext = p->pNext->pNext; free(q); q = NULL; return true;}
5.节点的排序
//排序算法void sort_list(PNODE pHead) { int len = length_list(pHead); PNODE p, q; int i, j, temp; 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) { temp = p->data; p->data = q->data; q->data = temp; } } } return;}
6. 测试代码
void main(void) { PNODE pHead = create_list(); if (isempty_list(pHead)) { printf("链表为空\n"); } else { printf("链表不为空\n"); } bool is_insert=insert_list(pHead, 2, 100); if (is_insert) { printf("链表在索引2出插入100 成功\n"); show_list(pHead); } else { printf("链表在索引2出插入100 失败\n"); } printf("删除节点索引:1\n"); bool is_del=delete_list(pHead, 1); if (is_del) { printf("删除节点索引:1 成功\n"); show_list(pHead); } else { printf("删除节点索引:1 失败\n"); }}