单向链表的相关操作(创建,遍历,插入,删除,逆置)

#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
using namespace std;
typedef struct node
{
    int ans;
    struct node *next;
}Node,*Linklist;
//初始化头结点
Linklist init(Linklist h)
{
    h=(Node *)malloc(sizeof(Node));
    h->next=NULL;
    return h;
}
//头插法建立单链表
Linklist creat_head()
{
    Linklist h,p;
    int temp;
    h=init(h);
    cout<<"输入数据(遇0结束)"<<endl;
    cin>>temp;
    while(temp)
    {
        p=(Node *)malloc(sizeof(Node));
        p->ans=temp;
        p->next=h->next;
        h->next=p;
        cin>>temp;
    }
    cout<<"头插入创建链表成功"<<endl;
    return h;
}
//尾插法建立单链表
Linklist creat_tail()
{
    Linklist h,p,q;
    int temp;
    h=init(h);
    q=h;
    cout<<"输入数据(遇0结束)"<<endl;
    cin>>temp;
    while(temp)
    {
        p=(Node *)malloc(sizeof(Node));
        p->ans=temp;
        q->next=p;
        q=p;
        cin>>temp;
    }
    q->next=NULL;
    cout<<"尾插入创建链表成功"<<endl;
    return h;
}
//遍历单链表
void display(Linklist h)
{
    Linklist p;
    p=h->next;
    while(p!=NULL)
    {
        cout<<p->ans<<endl;
        p=p->next;
    }
}
//删除操作
void delete_data(Linklist h)
{
    int temp;
    Linklist p,q;
    p=h;
    cout<<"输入要删除的元素值"<<endl;
    cin>>temp;
    while(p->next!=NULL)
    {
        if(p->next->ans==temp)
        {
            q=(Node *)malloc(sizeof(Node));
            q=p->next;
            p->next=p->next->next;
            free(q);
            break;
        }
        else p=p->next;
    }
    cout<<"删除成功"<<endl;
}
//插入操作
void add_data(Linklist h)
{
    Linklist p,q;
    int temp;
    p=h;
    cout<<"输入要插入的结点位置(在此节点之前插入元素)"<<endl;
    cin>>temp;
    for(int i=0;i<temp-1;i++)
      p=p->next;
    cout<<"输入要插入的元素"<<endl;
    cin>>temp;
    q=(Node *)malloc(sizeof(Node));
    q->ans=temp;
    q->next=p->next;
    p->next=q;
    cout<<"插入元素成功"<<endl;
}
//逆置单向链表
void Inverse_list(Linklist h)
{
   Linklist p,q;
   p=h->next;
   h->next=NULL;
   while(p!=NULL)
   {
     q=p;
p=p->next;
q->next=h->next;
h->next=q;
   }
   cout<<"逆置成功"<<endl;
}
int main()
{
    Linklist h;
    h=creat_head();
    display(h);
    h=creat_tail();
    display(h);
    delete_data(h);
    display(h);
    add_data(h);
    display(h);
    Inverse_list(h);
    display(h);
    return 0;
}


 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值