链接存储结构的线性表,它用一组地址任意的存储单元存放线性表中的数据元素,逻辑上相邻的元素在物理上不要求也相邻,不能随机存取。一般用结点描述:结点(表示数据元素) =数据域(数据元素的映象) + 指针域(指示后继元素存储位置)。
链表结构定义如下:
typedef struct LinkNode { DataType Data; struct LinkNode *next; }LinkNode, *pLinkNode,*pList;
1.初始化
void initLinkList(pList *pHead) { assert(pHead); *pHead = NULL; }
2.尾插法
int BuyNode(DataType x) //创建一个节点 { pLinkNode newNode = (pLinkNode)malloc(sizeof(LinkNode)); newNode->Data = x; newNode->next = NULL; } void pushBackList(pList *pHead, DataType x) //尾插法 { pLinkNode newNode = BuyNode(x); pLinkNode cur = *pHead; if (cur == NULL) { *pHead = newNode; } else { while (cur->next) { cur = cur->next; cur->next = newNode; } } }
3.头插法
void pushFront(pList *pHead, DataType x) //头插法 { pLinkNode newNode = BuyNode(x); if (*pHead) { *pHead = newNode; } else { newNode->next = (*pHead)->next; *pHead = newNode; } }
4. 尾删法
void popBack(pList *pHead) //尾删法 { pLinkNode cur = *pHead; if (*pHead == NULL) //无节点 { return; } else if ((*pHead)->next == NULL) //一个节点 { free(pHead); *pHead = NULL; } else //两个或两个以上的结点 { pLinkNode del = *pHead; while (cur->next->Data) { cur = cur->Data; } del = cur->Data; cur->next = NULL; free(del); } }
5.头删法
void popFront(pList *pHead) //头删法 { if (*pHead == NULL) return; else { pLinkNode del = *pHead; *pHead = (*pHead)->next; free(del); del = NULL; } }
6.在pos前插入x
void Insert(pList *pHead, pLinkNode pos,DataType x) { pLinkNode newNode = BuyNode(x); pLinkNode cur = *pHead; while (cur->next != pos) { cur = cur->next; } newNode->next = cur->next; cur->next = newNode; }
7.翻转链表
void Reverse(pList *pHead) //翻转链表---取出来,头插 { pLinkNode pnewHead = NULL; pLinkNode cur = *pHead; pLinkNode prev = NULL; while (cur) { prev = cur; cur = cur->next; prev->next = pnewHead; pnewHead = prev; } *pHead = pnewHead; }
时间: 2024-10-19 17:45:45