[原创]再来一个,链表~~~~
#include <stdio.h>#include <iostream.h>
#include <stdlib.h>
#include <iomanip.h>
#include <malloc.h>
typedef int Status;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
void initlist(LinkList &L,int len)
{
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
for(int i=len;i>0;--i)
{
LNode *p=(LinkList)malloc(sizeof(LNode));
p->data =i;
p->next=L->next;
L->next=p;
}
LNode *p=L;
for(int y=0;y<=len-1;y++)
{
cout<<p->data<<endl;
p=p->next;
}
}
void ListInsert(LinkList &L, int len, int e)
{
LNode *p=L;
int j=0;
while(p && j<len-1)
{
p=p->next;
++j;
}
if(!p||j>len-1)
cout<<"ERROR!!"<<endl;
LNode *s= (LinkList)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
for(int i=0;i<=len;i++)
{
cout<<p->data<<endl;
p=p->next;
}
}
void ListDelete(LinkList &L, int len,int &e)
{
LNode *p=L;
int j=0;
while(p->next && j<len-1)
{
p=p->next;
++j;
}
if(!(p->next)||j>len-1)
cout<<"ERROR"<<endl;
LNode *q=p->next;
p->next=q->next;
e=q->data;
free(q);
for(int i=0;i<len-2;i++)
{
cout<<setw(5)<<p->data;
*p++;
}
}
void main()
{
int len,n,t,k;
LinkList L;
cout<<"please input the length of the list \n";
cin>>len;
initlist(L,len);
cout<<"-------------------what do you want to do?--------------------"<<endl;
loop:
cout<<"input 1 to insert postion and element \n input 2 to delete a element \n input 3 to end the project"<<endl;
cin>>t;
if(t==1){
cout<<"\n please input the insert position and element:"<<endl;
cin>>len>>n;
ListInsert(L,len,n);
cout<<"\n";
}
if(t==2){
int e;
cout<<"please input the number you want to delete,\n";
cin>>e;
ListDelete(L,len,e);
cout<<"\n";
}
if(t==3)
exit(1);
else goto loop;
}