算法学习1 单链表
贴上源码记录下学习过程:
估计有很多不合适甚至错误的地方,欢迎指正:
单链表:
#define NodeType int class Node { public: Node() { next = NULL; value = 0; } ~Node() { } friend class LinkList; private: NodeType value; Node *next; }; class LinkList { public: LinkList() { head = new Node; } ~LinkList() { delete head; } //function: add node to the tail //val: the add node's value //return: success or not bool addNode(NodeType val) { bool ret = false; Node *node = new Node; if (node) { node->value = val; node->next = NULL; if (!head->next)//first node { head->next = node; } else { Node *temp = head; while(temp->next) { temp = temp->next; } temp->next = node; } ret = true; } return ret; } //function: delete all the match node //val: delete value //num: the number of delete nodes void delNode(const NodeType val,int &num) { bool ret = false; Node *loop = head; Node *pre = NULL; num = 0; while(loop->next) { pre =loop; Node *temp = loop = loop->next; if(val == temp->value)//find the match node { pre->next = temp->next; loop = pre; num++; delete temp; ret = true; } } if(!ret) { cout<<"No match Node or Empty List"<<endl; } } //function: clear the linklist void clear() { bool ret = false; Node *loop = head; Node *pre = NULL; while(loop->next) { pre =loop; Node *temp = loop = loop->next; pre->next = temp->next; loop = pre; delete temp; ret = true; } if (!ret) { cout<<"Empty List"<<endl; } } //function: output the linklist void output() { bool ret = false; Node *temp = head; while(temp->next) { temp = temp->next; cout<<temp->value<<" "; ret = true; } if (!ret) { cout<<"Empty List"<<endl; } } private: Node *head; }; void main() { LinkList link; link.addNode(5); link.output(); int delNum=0,delValue=5; link.delNode(delValue,delNum); cout<<"after del"<<" delNUm"<<delNum<<endl; link.output(); link.clear(); cout<<"after clear"<<endl; link.output(); }