C++实现链表
最后几天留在Intel,没什么事情,都是开开会。趁着闲功夫,把数据结构复习一下,写了一个list。时间仓促,有些地方考虑的可能没那么到位,望高手们指点。
#include <iostream> using namespace std; class listNode { public: listNode() { next = NULL; } int data; listNode *next; }; class mylist { private: unsigned int listlength; listNode *headNode; public: mylist(); listNode *getHead(); unsigned int length(); bool isEmpty(); void create(int data);//insert from the head void traverse();//traverse all nodes void insert(int data, int i);//insert data in location i void dele(int data);//delete data listNode *find(int data);//find data; }; mylist::mylist() { listlength = 0; headNode = NULL; } listNode *mylist::getHead() { return headNode; } unsigned int mylist::length() { return listlength; } bool mylist::isEmpty() { return (headNode == NULL); } void mylist::create(int data) { listNode *tempNode; tempNode = new listNode(); tempNode->data = data; if(headNode == NULL) headNode = tempNode; else { tempNode->next = headNode; headNode = tempNode; } listlength++; } void mylist::traverse() { listNode *iter; iter = headNode; if(iter == NULL) cout<<"list is empty"<<endl; else { while(iter != NULL) { cout<<iter->data<<endl; iter = iter->next; } } } void mylist::insert(int data, int i) { listNode *p, *index; p = new listNode(); index = headNode; if(i < 0 || i > listlength) cout<<"illegal location to insert"<<endl; else { p->data = data; for(int j = 0; j < i; j++) { index = index->next; } p->next = index->next; index->next = p; listlength++; } } void mylist::dele(int data) { listNode *iter, *iterNext; iter = headNode; iterNext = headNode->next; if(iter->data == data) { headNode = iterNext; delete iter; listlength--; return; } while(iterNext->data != data && iterNext != NULL) { iter = iter->next; iterNext = iterNext->next; } iter->next = iterNext->next; delete iterNext; listlength--; } listNode *mylist::find(int data) { listNode *iter; iter = headNode; while(iter->data != data && iter != NULL) iter = iter->next; return iter; } /*test for my list*/ int main() { mylist slist; if(slist.isEmpty()) cout<<"list is empty"<<endl; for(int i = 0; i < 5; i++) { slist.create(i); } slist.insert(5, 3); slist.dele(5); cout<<"list has "<<slist.length()<<" nodes"<<endl; slist.traverse(); cout<<"find 3 in my list:"<<slist.find(3)->data<<endl; return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
缓慢行走的蜗牛