插入的新节点非首节点
插入的新节点非首节点
// 创建新节点NODE* pNew = createNode(n);if (pNew == NULL){return head;}NODE* p = head;// 查找插入位置之前的节点指针int i = 0;for (i = 0; i < pos - 1; i++){p = p->pNext;}// 将新节点和后向节点连接pNew->pNext = p->pNext;// 将新节点和前向节点连接p->pNext = pNew;return head;
}
删除指定位置的节点
* NODE* head:
* int pos: 删除的位置(0认为是首节点)
* 返回类型: 返回新链表的首节点
*/
NODE* deleteNode(NODE* head, int pos)
{// 判断插入位置是否有效int count = calcNodeCount(head);if (pos < 0 || pos >= count){printf("delete pos error!\n");return head;}if (head == NULL){return NULL;}
删除步骤:
// 删除首节点if (pos == 0){// 1、记录待删除的首节点NODE* p = head;// 2、让首节点后移head = head->pNext;// 3、删除首节点free(p);p = NULL;// 4、返回新链表的首地址return head;}
删除其他节点
NODE* p = head;// 查找待删除节点之前的节点指针int i = 0;for (i = 0; i < pos - 1; i++){p = p->pNext;}//if (p->pNext == NULL)//{// return head;//}// 保存待删除节点的指针NODE* temp = p->pNext;// 将待删除节点前后两个节点连接起来p->pNext = temp->pNext;// 删除节点free(temp);temp = NULL;// 返回链表首节点return head;
}
修改指定位置的节点数据
* NODE* head: 链表首节点的地址
* int pos: 修改的位置(0认为是首节点)
* int newData: 新的数据
* 返回类型: 无
*/
void modifyNode(NODE* head, int pos, int newData)
{if (pos < 0){printf("modify pos error!\n");return;}NODE* p = head;int i = 0;for (i = 0; p != NULL && i < pos; i++){p = p->pNext;}if (p != NULL){p->num = newData;}
}
对链表进行排序(冒泡排序)
* NODE* head: 链表首节点的地址
* 返回类型: 无
*/
void sortList(NODE* head)
{if (head == NULL || head->pNext == NULL){return;}int num = calcNodeCount(head);int temp;int i, j;for (i = 0; i < num - 1; i++){NODE* p = head;for (j = 0; j < num - i - 1; j++){if (p->num > p->pNext->num){temp = p->num;p->num = p->pNext->num;p->pNext->num = temp;}p = p->pNext;}}
}int main()
{// 用于记录当前链表中首节点的地址NODE* pHead = NULL;// 将节点插入链表中:头插法insert_head1(5, &pHead);//insert_head1(4, &pHead);//insert_head1(3, &pHead);//insert_head1(2, &pHead);//insert_head1(1, &pHead);//pHead = insert_head2(-5, pHead);//pHead = insert_head2(-4, pHead);//pHead = insert_head2(-3, pHead);//pHead = insert_head2(-2, pHead);//pHead = insert_head2(-1, pHead);//// 将节点插入链表中:尾插法//pHead = insert_tail(1, pHead);//pHead = insert_tail(2, pHead);//pHead = insert_tail(3, pHead);//pHead = insert_tail(4, pHead);//// 将节点插入链表中:任意位置插入//// 假设位置 0 代表头插//pHead = insertNode(111, pHead, 0); // 前面14个元素//pHead = insertNode(222, pHead, 15); // 15//pHead = insertNode(333, pHead, 15); // 16//pHead = insertNode(444, pHead, 1); // 17//pHead = insertNode(555, pHead, 13); // 18//pHead = insertNode(666, pHead, 7); // 19//////// 按位置删除节点////pHead = deleteNode(pHead, 0);//// 修改节点数据////modifyNode(pHead, -1, 1111);//sortList(pHead);// 打印链表所有元素displayList(pHead);// 销毁整个链表distroyList(&pHead);displayList(pHead);return 0;
}