#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<string>
using namespace std;
typedef struct Node
{
int m_idata;
struct Node * m_pnext;
}Node,*pLinkList;
pLinkList CreateFromHead()
{
pLinkList L;
L = (pLinkList)malloc(sizeof(Node));
L->m_pnext = NULL;
bool bflag = true;
while(bflag)
{
cout <<"Please input the number(int),end of 0: "<<endl;
int _in;
cin >>_in;
if( 0 == _in)
{
bflag = false;
break;
}
Node *pstNode = (Node *)malloc(sizeof(Node));
pstNode->m_pnext = L->m_pnext;
pstNode->m_idata = _in;
L->m_pnext = pstNode;
}
return L;
}
void PrintList(pLinkList L)
{
if(NULL == L)
{
return ;
}
Node *p = L->m_pnext;
while(NULL != p)
{
cout <<p->m_idata<<" ";
p = p->m_pnext;
}
cout<<endl<<endl;
return ;
}
pLinkList CreateFromTail()
{
pLinkList L = (pLinkList)malloc(sizeof(Node));
L->m_pnext = NULL;
Node *r = L;
bool bcontinue = true;
while(bcontinue)
{
cout <<"Please input the number(int),end of 0: "<<endl;
int _in;
cin >>_in;
if( 0 == _in)
{
bcontinue = false;
break;
}
Node *s = (Node *)malloc(sizeof(Node));
s->m_idata = _in;
s->m_pnext = NULL;
r->m_pnext = s;
r = r->m_pnext;
}
return L;
}
pLinkList InsNode(pLinkList L)
{
if(NULL == L)
{
cout <<"The Link is empty,create it first."<<endl;
return NULL;
}
int ipos;
int idata;
cout <<"Please input the poszition :";
cin >>ipos;
cout <<"Please input the data:";
cin >>idata;
Node *pins = (Node*)malloc(sizeof(Node));
pins->m_pnext = NULL;
pins->m_idata = idata;
Node *p = L;
int i = 0;
while(i++ < ipos-1 && NULL != p)
{
p = p->m_pnext;
}
if(NULL == p || i != ipos)
{
cout<<"the input poszition is error"<<endl;
return L;
}
pins->m_pnext = p->m_pnext;
p->m_pnext = pins;
return L;
}
pLinkList DelNode(pLinkList L)
{
if(NULL == L)
{
return NULL;
}
int ipos;
cout <<"Please input the poszition :";
cin >>ipos;
int i = 0;
Node *p = L;
while(i++ < ipos - 1 && NULL != p->m_pnext)
{
p = p->m_pnext;
}
if(NULL == p->m_pnext || i != ipos )
{
cout<<"the input poszition is error"<<endl;
return L;
}
Node *pDel = p->m_pnext;
p->m_pnext = pDel->m_pnext;
free(pDel);
return L;
}
int main()
{
pLinkList L = NULL;
bool bContinue = true;
while(bContinue)
{
cout <<endl<<"************************************************************************"<<endl;
cout <<"Please input 1:CreateFromHead 2:CreateFromTail 3:Print "<<endl;
cout <<" 4:InsNode 5:DelNode 6:Sort 0:Exit";
cout <<endl<<"************************************************************************"<<endl;
int _inSelect;
cin>>_inSelect;
switch(_inSelect)
{
case 0:
bContinue = false;
break;
case 1:
L = CreateFromHead();
break;
case 2:
L = CreateFromTail();
break;
case 3:
PrintList(L);
break;
case 4:
InsNode(L);
break;
case 5:
DelNode(L);
break;
case 6:
break;
default:
break;
}
}
return 0;
}
单链表基本操作
最新推荐文章于 2020-12-15 20:10:33 发布