C语言链表

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct List{
int Data;
struct List*next;
};
//创建链表
struct List*Create(){
int n;
cout<<"请输入链表个数:";
scanf("%d",&n);
struct List*build;
struct List*head;
struct List*tail;
int t=1;
cout<<"请依次输入链表的数值:";
build=(struct List*)malloc(sizeof(struct List));
scanf("%d",&(build->Data));
build->next=NULL;
head=build;
tail=build;
while(t<n){
build=(struct List*)malloc(sizeof(struct List));
scanf("%d",&(build->Data));
build->next=NULL;
tail->next=build;
tail=build;
t++;
}
return head;
}
//输出函数
void output(struct List*print){
while(print!=NULL){
cout<<print->Data<<'-'<<'>';
print=print->next;
}
cout<<endl;
}
//查找函数
void Find(struct List*find){
int n=1,key;
cout<<"请输入要查找的元素:";
scanf("%d",&key);
struct List*p=find;
while(p!=NULL&&(p->Data!=key)){
p=p->next;
n++;
}
if(p==NULL) cout<<"不存在要查找的数 ";
else printf("要查找的数位于%d位 ",n);
}
//添加函数
struct List*Add(struct List*add){
int t=1,n,need;
cout<<"请输入要添加的元素:";
scanf("%d",&need);
cout<<"请输入添加的位置:";
scanf("%d",&n);
struct List*head=add;
struct List*p=add;
struct List*p1=NULL;
while(t<=n){
p1=p;
p=p->next;
t++;
}
struct List*addition;
addition=(struct List*)malloc(sizeof(struct List));
addition->Data=need;
p1->next=addition;
addition->next=p;
cout<<"插入后的链表为";
cout<<endl;
output(add);
return head;
}
//删除函数
struct List*Delete(struct List*rubbish){
int key;
struct List*q;
cout<<"请输入要删除的数:";
scanf("%d",&key);
struct List*head=rubbish;
struct List*p1=rubbish;
struct List*p2=NULL;
while(p1!=NULL&&(p1->Data!=key)){
p2=p1;
p1=p1->next;
}
if(p1==NULL) cout<<"未找到要删除的数";
else{
q=p1;
p2->next=p1->next;
p1=p1->next;
free(q);
}
cout<<"删除后的链表为:";
cout<<endl;
output(rubbish);
return rubbish;
}
//修改当前结点的值
void Set(struct List*fix){
int t=1,n,item;
cout<<"请输入要修改节点的位置:";
cin>>n;
cout<<"请输入修改后的节点值: ";
cin>>item;
struct List*p=fix;
struct List*p1=NULL;
while(t<=n){
p1=p;
p=p->next;
t++;
}
p1->Data=item;
cout<<"修改节点之后的链表为:";
cout<<endl;
output(fix);
}
//返回当前节点的值
int Return(struct List*value){
int t=1,n;
cout<<endl;
cout<<"请输入要返回节点的位置:";
cout<<endl;
cin>>n;
struct List*p=value;
struct List*p1=NULL;
while(t<=n){
p1=p;
p=p->next;
t++;
}
cout<<"当前的节点值为:"<<p1->Data;
return p1->Data;
}
//主函数
int main(){
int i;
struct List*create=Create();
cout<<"1.插入元素";
cout<<endl;
cout<<"2.删除元素";
cout<<endl;
cout<<"3.修改元素";
cout<<endl;
cout<<"4.查找结点";
cout<<endl;
cout<<"5.返回当前节点";
cout<<endl;
cout<<"6.结束";
cout<<endl;
while(1){
cout<<"your choice:";
cin>>i;
switch(i){
case(1):{
Add(create);
break;
}
case(2):{
Delete(create);
break;
}
case(3):{
Set(create);
break;
}
case(4):{
Find(create);
break;
}
case(5):{
Return(create);
break;
}
case(6):return 0;
}
}
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpjypx.html