#include<cstdio>
using namespace std;
struct Node{
int data;
Node *next;
};
typedef Node *Mylist;
void Createlist(Mylist &head,int n);//1
Mylist Copylist(Mylist L);//2
void InsertElem(Mylist &head,int index,int n);//3
void DeleteElem(Mylist &head,int index);//4
int FindElem(Mylist L,int index);//5
int GetLength(Mylist L);//6
void Printlist(Mylist L);//7
int main()
{
Mylist L;
int length;
int index,n;
int slt;//选择实现哪一个
while(1){
scanf("%d",&slt);
if(slt==-1)
break;
else
switch(slt){
case 1:
{
scanf("%d",&length);//输入所要构造链表的元素个数
Createlist(L,length);
printf("链表已创建,输入7可打印\n");
}
break;
case 2:
{
printf("已经复制,以下为复制后的链表\n");
Mylist newL;
newL=Copylist(L);
Printlist(newL);
}
break;
case 3:
{
scanf("%d %d",&index,&n);
InsertElem(L,index,n);
printf("已插入,输入7可打印插入后的链表\n");
}
break;
case 4:
{
scanf("%d",&index);
DeleteElem(L,index);
printf("已删除,输入7可打印删除后的链表\n");
}
break;
case 5:
{
scanf("%d",&index);
int value=FindElem(L,index);
printf("第%d个位置是元素%d",index,value);
}
break;
case 6:
GetLength(L);
break;
case 7:
Printlist(L);
break;
default: printf("请输入正确的实现选项!\n");
}
}
}
void Createlist(Mylist &head,int n)//n为所构造的链表元素个数
{
head=new Node;//构造空链表
//尾插法
/*head->next=NULL;
for(int i=0;i<n;i++)
{
Mylist p=new Node;
scanf("%d",&p->data);
p->next=head->next;
head->next=p;//即把p放到L前
}
*/
//头插法
Mylist p,q;
head->next=NULL;
p=head;
for(int i=0;i<n;i++)
{
q=new Node;
scanf("%d",&q->data);
p->next=q;
p=p->next;//因为头指针不能移动,所以移动p
}
p->next=NULL;
}
void Printlist(Mylist L)
{
Mylist p;
p=L;
while(p->next){
p=p->next;
printf("%d ",p->data);
}
printf("\n");
}
int GetLength(Mylist L)
{
Mylist p;
p=L;
int i=0;
while(p->next){
p=p->next;
i++;
}
return i;
}
Mylist Copylist(Mylist L)
{
Mylist newL;
Mylist tempL;
Mylist p,q;
tempL=L->next;
int newlength=GetLength(L);
newL=new Node;//newL 是头结点,不能动
newL->next=NULL;
p=newL;
for(int i=0;i<newlength;i++)
{
q=new Node;
q->data=tempL->data;
p->next=q;
p=p->next;//因为头指针不能移动,所以移动p
tempL=tempL->next;
}
p->next=NULL;
return newL;
}
void InsertElem(Mylist &head,int index,int n)
{
Mylist p;
p=head;
int j=0;
while(p&&j<index-1){
p=p->next;
j++;
}
Mylist s=new Node;
s->data=n;
s->next=p->next;
p->next=s;
}
void DeleteElem(Mylist &head,int index)
{
Mylist p,q;
p=head;
int j=0;
while(p->next&&j<index-1)
{
p=p->next;
j++;
}
q=p->next;
p->next=q->next;
delete q;
}
int FindElem(Mylist L,int index)
{
Mylist p;
p=L;
int j=0;
while(p->next&&j<index)
{
p=p->next;
j++;
}
return p->data;
}
以上是C++链表的基本操作,创建,插入,删除,查找……