C++ 实现单向链表

#include<iostream>
#include<string>
#include<stack>
using namespace std;
struct Node
{
int value;
Node* Next;
};
class List
{
private:
Node* head;
int count;
public:
List()
{
count=0;
head=NULL;
}
Node* Head()
{
return head;
}
void Create()
{
string str="";
int value;
Node *p=NULL;
while(1)
{
str="";
cout<<"Do you want to re-Enter the (Yes(Y)/No(N)) "<<endl;
cin>>str;
if(str=="Yes"||str=="Y"||str=="yes"||str=="y")
{
cout<<"Please input the value: ";
cin>>value;
if(head==NULL)
{
head=new Node;
head->value=value;
p=head;
p->Next=NULL;
}
else
{
while(p->Next!=NULL)
{
p=p->Next;
}
p->Next=new Node;
p->Next->value=value;
p->Next->Next=NULL;
p=p->Next;
}
}
else 
{
cout<<"Has stopped inputing,please continue to go ahead"<<endl;
break;
}
}
p=NULL;
}
int Number()
{
int number=0;
Node*p=head;
while(p!=NULL)
{
number+=1;
p=p->Next;
}
count=number;

return number;
}
void print_list()
{
Node*p=head;
while(NULL!=p)
{
cout<<p->value<<" ";
p=p->Next;
}
cout<<endl;
}
void reverse_output_list()
{
Node*p=head;
stack<Node*> s;
while(p->Next!=NULL)
{
s.push(p);
p=p->Next;
}
s.push(p);
while(!s.empty())
{
p=s.top();
s.pop();
cout<<p->value;
}
cout<<endl;
}
void reverse_list()
{
Node*p1=head,*p2=NULL,*p3;
while(p1!=NULL)
{
p3=p1->Next;
p1->Next=p2;
p2=p1;
p1=p3;
}
head=p2;//将p2赋值给头结点
}
void  DeleteNode(int value)
{
Node* p=head;
while(p!=NULL&&p->Next->value!=value)
{
p=p->Next;
}
if(p!=NULL)
{
Node*temp=p->Next;
p->Next=p->Next->Next;
delete temp;
}
else
{
cout<<"can't find the number"<<endl;
}
}
void reverse_output(Node*node)
{
if(node->Next==NULL)
{
cout<<node->value<<" ";
}
else
{
reverse_output(node->Next);
cout<<node<<" ";
}
}
void reverse_list_recursion(Node*nowNode, Node*foreNode)
{
if(nowNode->Next==NULL)
{
head=nowNode;
head->Next=foreNode;
}
else
{
reverse_list_recursion(nowNode->Next,nowNode);
nowNode->Next=foreNode;
}
}
void insert_node(int value1,int value2)
{
Node*p1=head,*p2;
while(p1!=NULL&&p1->Next->value!=value1)
{
p1=p1->Next;
}
if(p1!=NULL)
{

Node*newNode=new Node;
newNode->value=value2;
p2=p1->Next;
p1->Next=newNode;
newNode->Next=p2;
}
else
{
cout<<"can't found the "<<value1<<"in the list,please input the right number"<<endl;
}


}


};


int main()
{
List L;
L.Create();
L.print_list();
L.Number();
L.reverse_output_list();
L.reverse_list();
L.print_list();
Node*head=L.Head();
Node*temp=NULL;
L.reverse_list_recursion(head,0);
L.print_list();
int value;
cout<<"Please input the value to be deleted ";
cin>>value;
L.DeleteNode(value);
L.print_list();
int value1,value2;
cout<<"Please input the value of  the insert pos"<<endl;
cin>>value1;
cout<<"Please input the value to insert"<<endl;
cin>>value2;
L.insert_node(value1,value2);
L.print_list();
return 0;
};

猜你喜欢

转载自blog.csdn.net/u012782049/article/details/50366088
今日推荐