[c++]代码库
#include "stdafx.h"
#include <iostream>
using namespace std;
//C++动态链表的建立
class Book
{
public:
int num;
int price;
Book *next;
};
Book *p;
//创建头结点返回头结点地址给程序调用
Book* CreateHead()
{
Book *head,*p1,*p2;//定义三个指向Book的类,返回值给head
p1=new Book;
head=p1;
p2=p1;//将三个结点一起在椎中创建
cout<<"请输入图书编号,以0结束"<<endl;
cin>>p1->num;
if ( p1->num!=0 )
{
cout<<"请输入图书价格"<<endl;
cin>>p1->price;
}
else
{
delete p1;
p2=NULL;
return head;
}
while ( p1->num!=0 )
{
p2=p1;//这步很重要,意思为将P2设为当前结点,然后用p1继续创建,用培p2->next指向p1
p1=new Book;
cout<<"请输入图书编号,以0结束"<<endl;
cin>>p1->num;
if ( p1->num!=0 )
{
cout<<"请输入图书价格"<<endl;
cin>>p1->price;
}
p2->next=p1;
}
delete p1;
p2->next=NULL;
return head;
}
void Show ( Book *head )
{
while ( head!=NULL )
{
cout<<"图书编号为:"<<head->num<<",价格为:"<<head->price<<endl;
head=head->next;
}
}
//删除链表某个结点
void Delete ( Book *p,int num )
{
Book *temp;
if ( p->num==num )
{
temp=p;
p=p->next;
::p=p;
delete temp;
return;
}
while ( p )
{
if ( p->next==NULL )
{
cout<<"null"<<endl;
return;
}
if ( p->next->num==num )
{
temp=p->next;
p->next=temp->next;
delete temp;
cout<<"ok"<<endl;
return;
}
p=p->next;
}
cout<<"null"<<endl;
}
//链表的添加(这里假设直接添加到最尾段)
void Insert ( Book *p,int num,int price )
{
Book *temp=new Book;//这个结点用于添加编号和价格
Book *tem=new Book;//这个结点用于存放尾结点地址
while ( p )
{
tem=p;
p=p->next;
}
temp->num=num;
temp->price=price;
tem->next=temp;
temp->next=NULL;
}
int _tmain ( int argc, _TCHAR* argv[] )
{
p=CreateHead();
Show ( p );
cout<<endl;
cout<<"请输入要删除的编号"<<endl;
int num;
cin>>num;
Delete ( p,num );
Show ( p );
cout<<"请输入编号"<<endl;
cin>>num;
int price;
cout<<"请输入价格"<<endl;
cin>>price;
Insert ( p,num,price );
Show ( p );
system ( "pause" );
return 0;
}