首页 > 代码库 > 单向链表模板
单向链表模板
写个单向链表模板练练手:
#include <bits/stdc++.h>using namespace std;//create // delete // modify // searchclass Node{ public: int data; Node* ptr; Node(int elem= 0, Node* node= NULL){ this->data=http://www.mamicode.com/ elem; this->ptr= NULL; }};class MyList{ private: Node* head; Node* tail; int length; public: MyList(); ~MyList(); bool append(Node*); bool insert(int, Node*); void erase(int); void print(); int getLength(){return this->length;}};MyList::MyList(){ Node * init = new Node(0,NULL); this->head = new Node(); this->tail = new Node(); this->head = init; this->tail = init; this->length = 0;}MyList::~MyList(){ delete head; delete tail;}bool MyList::append(Node * n){ this->tail->ptr = n; this->tail = n; this->length++; return true;}bool MyList::insert(int pos, Node* n){ int i = 0; Node * tmp = new Node(); tmp = this->head; while(i != pos){ tmp = tmp->ptr; i++; } n->ptr = tmp->ptr; tmp->ptr = n; this->length++; return true;}void MyList::erase(int pos){ int i = 0; Node * tmp = new Node(); Node * del = new Node(); //del = this->head->ptr; tmp = this->head->ptr; while(i != pos - 1){ tmp = tmp->ptr; i++; } del = tmp->ptr; tmp->ptr = del->ptr; this->length--; delete del;}void MyList::print(){ int i = 0; cout << "len: " <<this->length << endl; Node * tmp = new Node(); tmp = this->head->ptr; while(i < this->length){ cout << tmp->data << endl; tmp = tmp->ptr; i++; } delete tmp;}int main(){ MyList ll; Node * node2 = new Node(2); Node * node3 = new Node(3); Node * node4 = new Node(4); ll.append(node2); ll.append(node3); ll.insert(1,node4); ll.print(); ll.erase(1); ll.print();}
单向链表模板
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。