C++.Homework.Classes and Objects.03

来源:互联网 发布:矩阵A2怎么算 编辑:程序博客网 时间:2024/05/27 20:42


/*======================ClassList.h===================*/

#include "iostream"#define NULL 0using namespace std;struct list{int data;list *next;};class List{private:list *head;                                                            //头指针list *p;                                                               //辅助指针public:List(){head=new list;head->data=0;head->next=NULL;};                   //初始化List(建立链表头节点)~List(){                                                               //删除Listp=head->next;while(p!=NULL){head->next=p->next;delete p;p=head->next;}delete head;};void InsertNode(int);                                                 //插入节点void DeleteNode(int);                                                 //删除节点void PrintList();                                                     //打印List};void List::InsertNode(int a){p=new list;p->data=a;p->next=head->next;head->next=p;}void List::DeleteNode(int a){list *q;                                                                //辅助指针p=head;while(p->next!=NULL){if(p->next->data!=a)p=p->next;else {q=p->next;p->next=p->next->next;delete q;}}};void List::PrintList(){p=head->next;while(p!=NULL){cout<<p->data<<endl;p=p->next;}}


/*======================main.cpp===================*/

#include"ClassList.h"void main(){List L1;int a,n;cout<<"Creatint a list...\nHow many number will you input?\n";cin>>n;cout<<"========================================================="<<endl;for(;n;n--){cin>>a;L1.InsertNode(a);}cout<<"========================================================="<<endl;L1.PrintList();cout<<"Which number will you delete?\n";cin>>a;cout<<"========================================================="<<endl;L1.DeleteNode(a);L1.PrintList();}

原创粉丝点击