(003)线性链表类

来源:互联网 发布:数学王子 知乎 编辑:程序博客网 时间:2024/05/22 23:56
(003)线性链表类
                                                                        2014/12/7        by jxlijunhao
#ifndefLINKED_LIST_H#define LINKED_LIST_H#include<iostream>using namespace std;//定义节点的类型template<class T>struct node{T data;node *next;};//定义线性表类template<class T>class linked_list{private:node<T> *head;public:linked_list();  //构造函数,建立空链表int flag_linked_list();//检测单链表的状态void print_linked_list();//打印链表void add_linked_list(T data);//将新的数据加入的表头T delete_head(); //删除链表头的元素void insert_linked_list(T,T); //在包含元素X的结点前插入新元素bvoid delete_linked_list(T); //删除包含元素x的结点};//构造函数,建立空链表template<class T>linked_list<T>::linked_list(){head=NULL;}//检测单链表的状态template<class T>int linked_list<T>::flag_linked_list(){if (head->next==NULL) return 0; //表示链表为空return 1;}//打印链表template<class T>void linked_list<T>::print_linked_list(){node<T> *p;p=head;if (head->next==NULL){cout<<"为空链表"<<endl;exit(0);}do {cout<<p->data<<endl;p=p->next;} while (p!=NULL);}//将新的数据加入的表头template<class T>void linked_list<T>::add_linked_list(T data){node<T> *p;p=new node<T>;p->data=data;p->next=head;head=p;} //删除链表头的元素template<class T>T linked_list<T>::delete_head(){T data;node<T> *p;if (head==NULL){cout<<"链表为空,无法删除"<<endl;exit(0);}p=head;data=p->data;head=p->next;delete p;return data;}//在包含元素X的结点前插入新元素btemplate<class T>void linked_list<T>::insert_linked_list(T x,T b){node<T> *p,*q;p=new node<T>;p->data=b;//当链表为空时if (head==NULL){head=p;p->next=NULL;return;}//当只用一个表头时if (head->data==x){p->next=head;head=p;return;}q=head;while (q->next!=NULL&&((q->next)->data))!=x){q=q->next;}p->next=q->next;q->next=p;return;}//删除包含元素x的结点template<class T>void linked_list<T>::delete_linked_list(T x){node<T> *p,*q;if (head==NULL){cout<<"链表为空"<<endl;exit(0);}if (head->data==x){p->next=head;delete head;head=p;exit(0);}q=head;while (q->next!=NULL&&((q->next)->data)!=x){q=q->next;}if (q->next==NULL) exit(0);p=q->next;q->next=p->next;delete p;}#endif 

#include "linked_list.h"int main(){linked_list<int>s;s.add_linked_list(10);s.add_linked_list(20);s.add_linked_list(30);s.add_linked_list(40);s.print_linked_list();s.delete_linked_list(10);s.print_linked_list();}


0 0