![]() |
#2
shl3052009-10-12 21:56
#include<iostream.h>
#include"malloc.h" struct node { int data; struct node *next; }; struct node *next,*null,*p,*L,*s,*q; int j,e,n,k; void create( ) { L=(struct node *)malloc(sizeof(struct node)); L->next=null; s=L; cout<<"请输入链表的元素(要求是整型,以-1结束输入):"<<endl; cin>>k; while(k!=-1) { p=(struct node *)malloc(sizeof(struct node)); p->data=k; s->next=p; s=p; cin>>k; } p->next=null; } void showlianbiao() { cout<<"您所建立的链表如下:"<<endl; p=L->next; j=0; while(p) { cout<<p->data<<" "; p=p->next; j++; } cout<<"链表元素个数:"<<j<<endl; } void insert( int i,int e) { cout<<"输入插入的位置i:"<<endl; cin>>i; cout<<"输入要插入的元素e:"<<endl; cin>>e; if(i<1||i>j) cout<<"插入位置错误!"<<endl; else { n=0; p = L->next; //加一句 while(n!=i) //条件写反了 { p=p->next;n++; } q=(struct node *)malloc(sizeof(struct node)); q->data=e; q->next=p->next; p->next=q; } p=L->next; while(p) { cout<<p->data<<" "; p=p->next; } } int main() { int i; cout<<"1--建立链表:"<<endl; cout<<"2--显示链表:"<<endl; cout<<"3--插入元素:"<<endl; cout<<"4--删除元素:"<<endl; cout<<"请选择:"<<endl; cin>>i; switch(i){ case 1: create(); main();break; case 2: showlianbiao();main();break; case 3: insert(i,e);main();break; case 4: cout<<" d"<<endl;main();break; } return 0; } |
插入的时候总是不对 求大虾们指正下 谢谢!!!
#include<iostream.h>
#include"malloc.h"
struct node
{
int data;
struct node *next;
};
struct node *next,*null,*p,*L,*s,*q;
int j,e,n,k;
void create( )
{
L=(struct node *)malloc(sizeof(struct node));
L->next=null;
s=L;
cout<<"请输入链表的元素(要求是整型,以-1结束输入):"<<endl;
cin>>k;
while(k!=-1)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=k;
s->next=p;
s=p;
cin>>k;
}
p->next=null;
}
void showlianbiao()
{
cout<<"您所建立的链表如下:"<<endl;
p=L->next;
j=0;
while(p)
{
cout<<p->data<<" ";
p=p->next;
j++;
}
cout<<"链表元素个数:"<<j<<endl;
}
void insert( int i,int e)
{
cout<<"输入插入的位置i:"<<endl;
cin>>i;
cout<<"输入要插入的元素e:"<<endl;
cin>>e;
if(i<1||i>j) cout<<"插入位置错误!"<<endl;
else {
n=0;
while(n==i)
{
p=p->next;n++;
}
q=(struct node *)malloc(sizeof(struct node));
q->data=e;
q->next=p->next;
p->next=q;
}
p=L->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
}
int main()
{
int i;
cout<<"1--建立链表:"<<endl;
cout<<"2--显示链表:"<<endl;
cout<<"3--插入元素:"<<endl;
cout<<"4--删除元素:"<<endl;
cout<<"请选择:"<<endl;
cin>>i;
switch(i){
case 1: create(); main();break;
case 2: showlianbiao();main();break;
case 3: insert(i,e);main();break;
case 4: cout<<" d"<<endl;main();break;
}
return 0;
}
[ 本帖最后由 lwp001 于 2009-10-12 17:03 编辑 ]