c++实现单链表及常用方法实现
来自https://blog.csdn.net/h294455907/article/details/80223345
这篇博客,做了一点小改动,用一个cpp实现的
#include<iostream> using namespace std; class ListNode { public : int data; ListNode *next; }; class List { public: List(); ~List(); void CreateList(); void Insert(int data,int index,bool flag = true); void Delete(int index); void printList(); void getData(int index); int getLength(); private: ListNode *head; }; List::List() { head = new ListNode(); head->next = NULL; cout<<"创建对象成功"<<endl; } List::~List() { ListNode *p = head, *s; while (p->next != NULL) { s = p->next; p = s->next; delete s; } delete p; delete head; } int List::getLength() { int len = 0; ListNode *p = head; while(p->next != NULL) { len++; p = p->next; } return len; } void List::CreateList() { int num,data; cout<<"请输入数据个数"; cin>>num; cout<<endl; cout<<"请输入数据"; cout<<endl; for(int i = 0;i<num;i++) { cin>>data; Insert(data,getLength()+2,false); } cout<<"List 创建完成"<<endl; } void List::Insert(int data,int index,bool flag) { ListNode *p = head, *s; if(index<=0) { cout<<"数据长度必须大于0"; return ; } if(getLength()+1<index) { while (p->next != NULL) { p = p->next; } s = (ListNode*)new ListNode[1]; s->data = data; s->next = NULL; p->next = s; if(flag!=false) { cout<<"链表长度为"<<getLength()-1<<",无法插入到第"<<index<<"个位置"; cout<<"现将数据"<<data<<"插入到表尾部"<<endl; } } else { for(int i =0;i<index-1;i++) { p = p->next; } s = (ListNode*)new ListNode[1]; s->data = data; s->next = p->next; p->next = s; cout<<"数据"<<data<<"插入第"<<index<<"个位置成功!"<<endl; } } void List::Delete(int index) { ListNode *p = head, *s; int i =0; if(index<=0||index>getLength()) { cout<<"元素不在表中"<<endl; return ; } while(i<index-1) { i++; p = p->next; } s= p->next; p->next = s->next; cout<<"第"<<index<<"个元素删除成功!"<<endl; delete s; } void List::printList() { ListNode *p = head; cout<<"printList:"<<endl; if(p->next==NULL) { cout<<"空链表"<<endl; return ; } p= p->next; while(p!= NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; } void List::getData(int index) { ListNode *p = head; if(index<=0||index>getLength()) { cout<<"元素不在表中"<<endl; return ; } for(int i = 0;i<index;i++) { p = p->next; } cout<<"第"<<index<<"个元素为"<<p->data<<endl; } int main() { List list; list.CreateList(); list.printList(); list.Insert(10,2); list.Insert(20,10); list.printList(); list.Delete(5); list.printList(); list.getData(4); cout<<"目前链表长度为"<<list.getLength()<<endl; return 0; }