C++实现数据结构中的单链表

来源:互联网 发布:计量型数据 编辑:程序博客网 时间:2024/06/01 21:30
#include<iostream>using namespace std;//定义一个节点类class Node{public:int data;Node *next;Node():next(NULL){}Node(const int &value,Node *next_=NULL):data(value),next(next_){}};//定义一个单单链表class Linklist{private:Node *head;public:Linklist():head(new Node){}//判断链表是否为空bool is_empty()const{if(head->next==NULL)return true;return false;}//判断链表的长度int get_length(){int length=0;Node *p=head->next;while(!p){++length;p=p->next;}return length;}//返回第i=个元素的值Node *get_value(int i){if(i<=0||i>get_length()){cout<<"error"<<endl;return NULL;}else{Node *p=head->next;int j=1;while(p&&j<i){p=p->next;++j;}return p;}}  //在第i个位置之前插入相应元素的值bool insert_pos(int value,int i){if(i<=0||i>get_length()){cout<<"无法插入相应的元素"<<endl;return false;}else{int j=1;Node *p=head;while(p&&j<i){p=p->next;++j;}Node *newnode=new Node(value);newnode->next=p->next;p->next=newnode;return true;}}//下面顶一个采用尾插法插值的函数void insert(int value){Node *p=head;Node *q=p;while(p){   q=p;p=p->next;}Node *newnode=new Node(value);q->next=newnode;}void display(){   if(head->next==NULL)return ;Node *p=head->next;while(p){cout<<p->data<<'\t';p=p->next;}}//定义一个删除某个节点的函数void delete_node(int value){Node *pos_node=NULL;Node *q=head;Node *p=head->next;while(p){if(p->data==value){pos_node=p;break;}q=p;p=p->next;}if(!p){cout<<"找不到要删除的结点"<<endl;return ;}Node *s;q->next=pos_node->next;}};int main(){   Linklist l1;l1.insert(1);l1.insert(2);l1.insert(3);l1.insert(4);l1.insert(5);l1.insert(6);l1.insert(7);l1.display();cout<<endl;l1.delete_node(4);l1.display();system("pause");return 0;}


0 0
原创粉丝点击