本代码是对链表的建立,及删除,插入,寻找,输出的函数表达
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct node{
int date;
struct node *next;
}node;//建立节点
node *creatline(node *head,int n)
{
node *p;
cout<<"请输入对应链表的数值"<<endl; //输入初始链表的长度
for(int i=1;i<=n;i++)
{
p=(node*)malloc(sizeof(node));
int a;
cin>>a;
p->date=a;
p->next=head->next;
head->next=p;//前插法创建链表
}//循环创建链表
return head;
}
void printfline(node *head)
{
node *p;
p=head->next;//指针p指向第一个数据节点
while(p!=head)
{
cout<<p->date<<" ";
p=p->next;//p指针指向下一个节点
}//不断输出
cout<<endl;
}
node *san(node *head)//删除函数
{int k;
cout<<"请输入删掉值得位置"<<endl;
cin>>k;//k为删掉的位置
node *p,*q,*l;
p=head->next;
k--;//找到被删节点的前一个节点循环k-1次
while(p!=head)
{
while(k--)
{l=p;//循环l指向目标节点前一个节点
p=p->next;
}
q=l->next;//用指针q暂存目标点
l->next=l->next->next;//连接节点
free(q);//释放节点
break;
}
return head;
}
node *cha(node *head)
{int k,n;
node *p,*q,*l;
q=(node *)malloc(sizeof(node));//插入需要建立新节点
cout<<"请输入插入的值和要插入的位置"<<endl;
cin>>n>>k;
q->date=n;
p=head->next;
k--;
while(p!=head)
{
while(k--)
{ l=p;
p=p->next;
}//同上找到目标节点的前一个节点
q->next=l->next;
l->next=q;//重新连接链表
break;
}
return head;
}
node *find(node *head)
{
int n;
cout<<"请输入要查询值的位置"<<endl;
cin>>n;//输入查询位置
node *p,*l;
p=head->next;
while(p!=head)
{
while(n--)
{l=p;
p=p->next;
}
break;//找到直接输出
}
cout<<l->date;
}
int main()
{
node *head,*p,*q;
head=(node *)malloc(sizeof(node));//头结点创建
head->next=head;
int b;
cout<<"请输入初始链表的长度"<<endl;
cin>>b;
creatline(head,b); //创建初始链表
cout<<"输出链表"<<endl;
printfline(head);
cha(head);//插入节点
cout<<"输出修改后链表"<<endl;
printfline(head);
san(head);//删除节点
cout<<"输出修改后链表"<<endl;
printfline(head);
find(head);//查找链表
return 0;
}