原文引用:https://blog.csdn.net/qq_42366014/article/details/105000993
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct mylist {
int v;
struct mylist *next;
}MY_LIST;
void InitList(MY_LIST **pHead);
void InsertItem(MY_LIST *pItem, int a, MY_LIST *pHead);
void PrintList(MY_LIST *pHead);
void DelItem(MY_LIST *pHead, int item);
void CleanMyList(MY_LIST *pHead);
void ReverseMyList(MY_LIST *pHead);
void SortList(MY_LIST *pHead);
MY_LIST *FindElem(MY_LIST *pHead, int a, bool pos);
//初始化一个空链表,以及一个链表头节点(非元节点)
void InitList(MY_LIST **pHead) {
*pHead = (MY_LIST *)malloc(sizeof(MY_LIST));
if (NULL == *pHead) {
printf("pHead Failed!\n");
exit(1);
}
(*pHead)->next = NULL;
return;
}
//链表的遍历
void PrintList(MY_LIST *pHead) {
if (pHead->next == NULL) {
printf("Empty List!\n");
return;
}
MY_LIST *temp = pHead->next; //这个才是:元节点
while (temp) {
printf("***Current Item is %d***\n", temp->v);
temp = temp->next;
}
}
//查找给定元素的节点信息:pos 标记返回当前节点还是前一个节点
MY_LIST *FindElem(MY_LIST *pHead, int a,bool pos) {
MY_LIST *temp = pHead;
MY_LIST *prev = NULL;
while (temp) {
if (temp->v == a) break;
prev = temp;
temp = temp->next;
}
return (!pos)?prev:temp;
}
//指定节点位置之后插入新节点,若无则入队尾
void InsertItem(MY_LIST *pItem, int a, MY_LIST *pHead) {
MY_LIST *node = (MY_LIST *)malloc(sizeof(MY_LIST));
node->v = a;
node->next = NULL;
//移动指针到pItem,或者到队尾
MY_LIST *end = pHead;
while (end) {
if (end->next == NULL) break;
if (end->next == pItem) {
end = pItem;
break;
}
end = end->next;
}
node->next = end->next;
end->next = node;
printf("***Add Item is %d***\n", node->v);
return;
}
//删除指定元素节点
void DelItem(MY_LIST *pHead, int item) {
MY_LIST *pItemPrev = FindElem(pHead, item, 0);
if (pItemPrev == NULL)
printf("%d is not exists!\n", item);
MY_LIST *pItem = pItemPrev->next; //当前节点
pItemPrev->next = pItem->next; //重置前一节点的next指针
free(pItem);
pItem = NULL;
}
//销毁除头节点之外的所有链表节点
void CleanMyList(MY_LIST *pHead) {
MY_LIST *temp = pHead->next;
MY_LIST *pNext = NULL;
while (temp) {
pNext = temp->next;
pHead->next = pNext;
free(temp);
temp = pNext;
}
if (pHead->next == NULL)
printf("Clean MyList Done!\n");
return;
}
//链表反转
void ReverseMyList(MY_LIST *pHead) {
MY_LIST *cur = pHead->next;
MY_LIST *curNext = NULL;
MY_LIST *temp = NULL;
while (cur) {
curNext = cur->next;
cur->next = temp;
temp = cur;
cur = curNext;
}
pHead->next = temp;
}
//链表排序
void swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void SortList(MY_LIST *pHead) {
MY_LIST* pPrev = pHead;
MY_LIST* pEnd = NULL;
MY_LIST* pCur = NULL;
while (pHead != pEnd) {
pPrev = pHead;
while (pPrev->next != pEnd) {
pCur = pPrev->next;
if (pPrev->v < pCur->v) swap(&pPrev->v, &pCur->v);
pPrev = pPrev->next;
}
pEnd = pPrev;
}
}