欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

[数据结构与算法] - 链表

最编程 2024-05-05 22:24:30
...
#include "MyList.hpp" #include <iostream> using namespace std; void printList(pNode headNode) { cout << "*** printList ****" << endl; pNode tempNode, curNode; if (nullptr == headNode) { cout << "*** printList error ****" << endl; return ; } curNode = headNode->next; cout << "*** [printList]: "; while (curNode) { cout << curNode->data << " , "; tempNode = curNode; curNode = tempNode->next; } cout << endl; return ; } pNode initList(int num) { cout << "*** InitList ****" << endl; pNode headNode, tempNode, curNode; headNode = (pNode)malloc(sizeof(Node)); if (nullptr == headNode) { cout << "*** init error ****" << endl; return nullptr; } headNode->next = nullptr; curNode = headNode; for (int i = 1; i <= num; i++) { tempNode = (pNode)malloc(sizeof(Node)); if (nullptr == tempNode) { cout << "*** init error ****" << endl; return nullptr; } tempNode->data = i; tempNode->next = nullptr; curNode->next = tempNode; curNode = tempNode; tempNode = nullptr; } return headNode; } pNode searchList(pNode headNode, int data) { cout << "*** searchList ****" << endl; pNode tempNode, curNode; if (nullptr == headNode) { cout << "[searchList] error." << endl; return nullptr; } curNode = headNode->next; while (curNode) { if (data == curNode->data) { cout << "[searchList] suc. data: " << data << endl; return curNode; } tempNode = curNode; curNode = tempNode->next; } cout << "[searchList] not find. data: " << data << endl; return nullptr; } void reverseList(pNode node) { cout << "*** reverseList ****" << endl; pNode curNode, curNextNode; if (nullptr == node) { cout << "*** reverseList error ****" << endl; return; } curNode = node->next; node->next = nullptr; while (curNode) { curNextNode = curNode->next; curNode->next = node->next; node->next = curNode; curNode = curNextNode; } cout << "*** reverseList ok ****" << endl; return; } void testList(void) { cout << "*** Test_List ****" << endl; pNode headNode = initList(5); if (nullptr == headNode) { cout << "*** InitList error ****" << endl; } printList(headNode); pNode node = searchList(headNode, 2); reverseList(node); printList(headNode); }