单链表处理

随便写了点,写得不好,遗忘的时候,回来看看:

#include <iostream> using namespace std; typedef struct Node { int age; Node *pNext; }ListNode, *LinkList; //链表处理函数 LinkList CreateLinkList(); void Append(LinkList const head, int data); //添加(至末尾) void Insert(LinkList const head, int data, int pos); //插入 void Delete(LinkList const head, int pos); //删除 void Print(LinkList const head); //输出 void ClearLinkList(LinkList head); //清空 int main(int argc, char *arv[]) { LinkList head = NULL; //每次都从head开始输出 cout << "输出创建前的表:" << endl; Print(head); head = CreateLinkList(); //输出 cout << "输出创建后的表:" << endl; Print(head); //添加(至末尾) for (int i = 1; i < 4; ++i) { Append(head, i); } //输出 cout << "输出添加3个元素后的表:" << endl; Print(head); //插入 Insert(head, 12, 2); //输出 cout << "输出在2号元素后插入数据12的表:" << endl; Print(head); //删除 Delete(head, 2); //输出 cout << "输出将2号元素删除后的表:" << endl; Print(head); //清空 ClearLinkList(head); head = NULL; //输出 cout << "Clear表:" << endl; Print(head); getchar(); return 0; } LinkList CreateLinkList() { ListNode *p; p = new ListNode; p->age = 0; p->pNext = NULL; return p; } void Append(LinkList const head, int data) { if (!head) { ClearLinkList(head);//链表若为空,则创建 } ListNode *pNode = new ListNode; pNode->age = data; pNode->pNext = NULL; ListNode *pEnd = NULL; pEnd = head; while (pEnd->pNext)//找到末节点 { pEnd = pEnd->pNext; } pEnd->pNext = pNode; } void Insert(LinkList const head, int data, int pos) { ListNode *p = head; if (!head) { return;//链表为空 } else { while(p->age != pos - 1) { p = p->pNext; if (!p) { return;//到了链表末端 } } //插入 ListNode *pNode = new ListNode; pNode->age = data; pNode->pNext = p->pNext; p->pNext = pNode; } } void Delete(LinkList const head, int pos) { ListNode *p = head; if (!head) { return; } else { while(p->age != pos - 1) { p = p->pNext; if (!p) { return;//末端 } } //删除 ListNode *pNode = p->pNext; p->pNext = pNode->pNext; delete pNode; } } void Print(LinkList const head) { if (!head) { cout << "LinkList is Null!" << endl; } else { ListNode *p = head; do { cout << p->age << endl; p = p->pNext; } while (p); } } void ClearLinkList(LinkList head) { if (!head) { return; } ListNode *pNode = NULL; ListNode *pNodeNext = NULL; pNode = head; do { pNodeNext = pNode->pNext; delete pNode; pNode = pNodeNext; } while (pNode); head = NULL; }

上一篇:Windows云服务器CPU使用率高的问题一例


下一篇:nginx default跳转