用C++ 实现链表:
首先功能分析: 构造,清理,增删改查,求大小 判断空 ,取头取尾
#include <iostream> using namespace std; typedef int T; //链表类 class LinkedList { struct Node { T data; Node* next; Node(const T& t):data(t),next(NULL) { } }; public: //构造 析构 清空 LinkedList():head(NULL) { } ~LinedList() { clear(); } void clear() { } //增(insertBack insertFront)删改查(find) void insertFront(const T& t) { } void insertBack(const T& t) { } void erase(const T& t) { } void update(const T& t,const T& target) { } unsigned int find(const T& t) { unsigned int position=0; return position; } //判断empty 求size 遍历(travel) bool empty() { } unsigned int size() { int size=0; return size; } void travel() { } //取头 取尾 T getHead() { } T getTail() { } //去指定位置取指针 辅助作用 Node* getPointer(int position) { return NULL; } private: //头指针 最重要的部分 Node* head; }; int main() { }
功能添加:
#include <iostream> using namespace std; typedef int T; //链表类 class LinkedList { struct Node { T data; Node* next; //初始化data next 阻止垃圾数据 Node(const T& t=T()):data(t),next(NULL) { } }; public: //构造 析构 清空 LinkedList():head(NULL) { } ~LinkedList() { clear(); } void clear() { Node *p=head; while (p!=NULL) { Node *q = p->next; delete p;//释放p所在空间 p=q; } } //判断empty 求size 遍历(travel) bool empty() { //判断头指针是否为空 为空表示链表不存在 return head==NULL ? true : false; } unsigned int size() { unsigned int size=0; Node* p =head; while (p!=NULL) { size++; pp=p->next; } return size; } void travel() { //利用while循环一次次的输出来,直到指针为NULL结束 Node* p = head; while (p!=NULL) { cout<<p->data<<endl; pp=p->next; } } //增(insertAfter insertFront)删改查(find) void insertFront(const T& t) { Node* p = new Node(t); p->next=head; //讲头指针所指向的地址给p的next head = p; //让*p作为头 } void insertAfter(const T& t) { Node *p = new Node(t); Node *tail = getPointer(size()-1); tail->next = p; } void erase(const T& t) { unsigned int position = find(t); Node* cur = getPointer(position); if (position!=0) { Node* pre = getPointer(find(t)-1); pre->next = cur->next; }else{ head = cur->next; } delete cur; } void update(const T& t,const T& target) { Node *p=getPointer(find(target)); p->data=t; } unsigned int find(const T& t) { unsigned int position=0; Node* p = head; while(p!=NULL) { if (p->data==t) { return position; } pp=p->next; position++; } return position; } //取头 取尾 T getHead() { return head->data; } T getTail() { Node *p=getPointer(this->size()-1); return p->data; } //去指定位置取指针 辅助作用 Node* getPointer(int position) { Node* p =head; for(int i = 0;i<position;i++) { pp=p->next; } return p; } private: //头指针 最重要的部分 Node* head; }; int main() { }