链表
#include <iostream>
#include <string>
using namespace std;
#define NULL 0
class node
{
public:
node * createlink();
void printlink(node *head);
node * insertlink(node *head,string num1);
node * dellink(node *head,string num2);
private:
string data;
node* next;
};
node* node::createlink()
{
node *head=NULL;
node *p1,*p2;
p1=p2=new node;
cout<<"输入链表数据并以$为结束标志"<<endl;
cin>>p1->data;
while(p1->data!="$")
{
if(head==NULL)
head=p1;
else
p2=p1;
p1=new node;
cin>>p1->data;
p2->next=p1;
}
p2->next=NULL;
return head;
}
void node::printlink(node* head)
{
node *p1=head;
if(head==NULL)
cout<<"链表为空!"<<endl;
else
{
cout<<"输出链表:"<<endl;
do
{
cout<<p1->data<<" ";
p1=p1->next;
}while(p1!=NULL);
cout<<endl;
}
}
node * node::insertlink(node *head,string num1)
{
if(head==NULL)
cout<<"链表为空!"<<endl;
else
{
node *p1,*p2,*p;
p1=p2=head;
while(p1!=NULL)
{
if(num1<=head->data)
{
p1=new node;
p1->data=num1;
p1->next=head;
head=p1;
break;
}
if(num1<=p1->data)
{
p=new node;
p2->next=p;
p->data=num1;
p->next=p1;
break;
}
if(p1->next==NULL&&num1>p1->data)
{
p2=p1;
p1=new node;
p1->data=num1;
p1->next=NULL;
p2->next=p1;
}
p2=p1;
p1=p1->next;
}
}
return head;
}
node* node::dellink(node *head,string num2)
{
if(head==NULL)
cout<<"链表为空!"<<endl;
else
{
node *p1,*p2,*p;
p=p1=p2=head;
while(p1!=NULL)
{
if(head->data==num2)
{
p=p1;
p1=p1->next;
head=p1;
}
else
if(p1->data==num2)
{
p=p1;
p1=p1->next;
p2->next=p1;
}
else
{
if(p->data==num2) break;
if(p1->next==NULL)
{cout<<"要删除的数据不在链表中!"<<endl;break;}
p2=p1;
p1=p1->next;
}
}
}
return head;
}
void main()
{
node link;
node *head;
head=link.createlink();
link.printlink(head);
string num1;
cout<<"输入要插入的数据:";cin>>num1;
head=link.insertlink(head,num1);
link.printlink(head);
string num2;
cout<<"输入要删除的数据:";cin>>num2;
head=link.dellink(head,num2);
link.printlink(head);
}
注意:
- 指针变量作实参传递时,也只是传递给一个指针变量,而原实参变量并不会因形参的变化而变化;
- 要区分指针变量之间的传递以及对指针所指空间的操作之间是不同的;
- 定义指针变量时要同时对其指明指向;