链表自实现:插入,删除

// nodelist.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" struct Node { int value; Node * _next; }; class list { private: Node *head; Node *tail; public: list() { } ~list() { } public: Node* create(int len); Node*getHead() { return head; } Node*getTail() { return tail; } public: void insert(int value); void del(int value); }; Node* list::create(int len) { for(int i=0;i<len;i++) { Node *p = new Node; p->value = i; p->_next = NULL; if(i==0) { head = tail = p; } else { tail->_next = p; tail = p; } } return head; } void list::insert(int value) { Node*p = new Node; p->value = value; p->_next = NULL; if(head == NULL) head = tail = p; else tail->_next = p; tail = p; } void list::del(int value) { if(head == NULL) return; Node *cur=head,*pre,*tmp; if(head->value == value) { tmp = head; head = head->_next; delete tmp; return; } while(cur->_next!=NULL && cur->value != value) { pre = cur; cur = cur->_next; } if(cur == NULL) return; if(cur == tail) { tail = pre; return; } pre->_next = cur->_next; tmp = cur; delete tmp; } void print(Node *p) { while(p!=NULL) { printf("value:%d/n",p->value); p = p->_next; } } int _tmain(int argc, _TCHAR* argv[]) { list m_list; Node *list = m_list.create(10); Node *p = m_list.getHead(); print(p); system("pause"); m_list.del(5); print(p); system("pause"); m_list.insert(5); print(p); system("pause"); return 0; }

你可能感兴趣的:(链表自实现:插入,删除)