#include "stdafx.h"
#include <iostream>
#include <cstdlib>
using namespace std;
class ListNode //定义结点
{
public:
ListNode* next;
int value;
}*pBase,*pCurrent;
ListNode* ListCreation(int n,int _Order) //建一个表
{
if(_Order)
{
for(int i=0;i<n;++i)
{
if(i==0)
{
pBase=new ListNode;
pBase->value=i;
pBase->next=NULL;
pCurrent=pBase;
}
else
{
ListNode* p=new ListNode;
p->value=i;
p->next=NULL;
pCurrent->next=p;
pCurrent=p;
}
}
return pBase;
}
else{
for(int i=n-1;i>=0;--i)
{
if(i==n-1)
{
pBase=new ListNode;
pBase->value=i;
pBase->next=NULL;
pCurrent=pBase;
}
else
{
ListNode* p=new ListNode;
p->value=i;
p->next=NULL;
pCurrent->next=p;
pCurrent=p;
}
}
return pBase;
}
}
/*ListNode* insert_elem(ListNode* _pBase,int _elem,int _Order)//ok,插入一个元素,并保持原有的顺序;分两种,每种里面又有三种子情况*/
{
if(_Order){
ListNode* _pCurrent=_pBase;
for(;_pCurrent->next
{
ListNode* _temp=_pCurrent;
_pCurrent=_pCurrent->next;
if(_elem >= _temp->value && _elem<= _pCurrent->value)//ok
{
ListNode* p=new ListNode;
p->value=_elem;
p->next=_pCurrent;
_temp->next=p;
return _pBase;
}
else{
if(_elem<=_pBase->value)
{
ListNode* p=new ListNode;
p->next=_pBase;
p->value=_elem;
return p;
}
if(!_pCurrent->next)//OK
{
ListNode* p=new ListNode;
p->next=NULL;
p->value=_elem;
_pCurrent->next=p;
return _pBase;
}
}
}
}//1
else//进入降序处理
{
ListNode* _pCurrent=_pBase;
for(;_pCurrent->next//进入循环测试
{//for
ListNode* _temp=_pCurrent;
_pCurrent=_pCurrent->next;
if(_elem <= _temp->value && _elem>= _pCurrent->value)//ok
{
ListNode* p=new ListNode;
p->value=_elem;
p->next=_pCurrent;
_temp->next=p;
return _pBase;
}
else{//1
if(_elem>=_pBase->value)
{
ListNode* p=new ListNode;
p->next=_pBase;
p->value=_elem;
return p;
}
if(!_pCurrent->next)//OK
{
ListNode* p=new ListNode;
p->next=NULL;
p->value=_elem;
_pCurrent->next=p;
return _pBase;
}
}//1
}//for
}//0
}
void displaylist(ListNode* _pBase)//显示结果
{
ListNode* p=_pBase;
for(;p->next
{
cout<<"p->value:"<<p->value<<endl;
p=p->next;
}
cout<<"p->value:"<<p->value<<endl;
}
int main()
{ int Continue=1;
for(;Continue
{
int Order; //排序标准,1 为升序,0为将序
for( ;
{
cout<<"请输入内置链表的顺序(1为升序,0为降序):";
cin>>Order;
if(Order==1||Order==0)
{
int Size=-5;
cout<<"请输入你将建的链表的大小:";
cin>>Size;
for(;!(Size>=0&&Size<=256);cout<<endl<<"输入错误,本程序只支持0~256大小的链表!!!请重新输入:"
cin>>Size;
cout<<"初始化链表。。。"<<endl;
ListCreation(Size,Order);
break;
}
else
cout<<"输入错误,请重新输入!!!"<<endl;
}
/*Order=WhetherA(pBase);//1为升序,0为将序
if(Order)
cout<<"Order:"<<"升序"<<endl;
else
cout<<"Order:"<<"降序"<<endl;
*/
int inputvalue;
displaylist(pBase);
cout<<"input the value you want to insert:";
cin>>inputvalue;
pBase=insert_elem(pBase,inputvalue,Order);
displaylist(pBase);
cout<<endl;
cout<<"是否继续1(Y)/0(N):";
cin>>Continue;
if(Continue!=1)
{Continue=0;
return 0;
}
}
return 1;
}