要求:实现单链表的插入和删除
分析:熟悉链表的基本操作。
代码如下:
#include<iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
Node *p1,*p2=new Node;
Node *Linklist=new Node; //Global variable
int main()
{
void InitializeNode();
void InsertNode();
void DeleteNode();
InitializeNode();
InsertNode();
DeleteNode();
delete p1;
delete p2;
delete Linklist;
return 0;
}
void InitializeNode()
{
int n=0,i=1;
p1=p2;
cout<<"Please input numbers,Crtl+Z to end."<<endl;
while (cin>>n){ //Dymatic linklist
if (i==1){
Linklist=p1;
p2->next =p1;
p1->data =n;
p2=p1;
p1=new Node;
i++;
}
else {
p2->next =p1;
p1->data =n;
p2=p1;
p1=new Node;
}
}
p2->next =NULL; //Make the "next" element of tail node NULL
p1=Linklist;
while(p1 ){ //Output linklist
cout<<p1 ->data;
if ((p1->next) !=NULL){
cout<<"->";
p1=p1->next ;
}
else {
cout<<endl;
return;
}
}
}
void InsertNode()
{
cin.clear();
int pos=0,i=0,n=0;
cout<<"Please input the position you want to insert node:"<<endl;
cin>>pos;
cout<<"Please input the data:"<<endl;
cin>>n;
p1=Linklist;
for (i=1;i<pos;++i){ //Move pointer to right position
p1=p1->next ;
}
p2=new Node; //Insert node
p2->data =n;
p2->next =p1->next ;
p1->next=p2;
p1=Linklist;
while(p1 ){ //Output linklist
cout<<p1 ->data;
if ((p1->next) !=NULL){
cout<<"->";
p1=p1->next ;
}
else {
cout<<endl;
return;
}
}
}
void DeleteNode()
{
int pos=0,i=0;
cout<<"Please input the position of the node you want to delete:"<<endl;
cin>>pos;
p1=Linklist;
for (i=1;i<pos-1;++i){ //Move pointer to right position
p1=p1->next;
}
p1->next=p1->next->next; //Delete node
p1=Linklist;
while(p1 ){ //Output linklist
cout<<p1 ->data;
if ((p1->next) !=NULL){
cout<<"->";
p1=p1->next ;
}
else {
cout<<endl;
return;
}
}
}