无头结点单链表的定义,创建和遍历

先放上运行截图哈!

上面的是头插法的运行结果,下面是尾插法的运行结果

下面是完整代码:

#include <iostream>
#include <stdio.h>

using namespace std;

/*链表结构体定义*/
typedef int ElemType;
struct List{
    ElemType data;
    struct List *next;
};
typedef struct List *list;

/*初始化无头结点单链表*/
bool f_initialize(list &L){
    L=NULL;
    return true;
}
/*判断无头结点链表是否为空*/
bool f_judge(list &L){
    if(L==NULL){
        return true;
    }
    else{
        return false;
    }
}

/*建立链表*/   //头插和尾插都需要头结点
    /*头插法*/    //插入到头结点后面!!!
        list f_headinsert(list &L){
            L=(list)malloc(sizeof(List));
            L->next=NULL;
            ElemType x;
            cout<<"\n输入节点数据,-1表示结束输入:\n";
            cin>>x;
            while(x!=-1){
                list p=(list)malloc(sizeof(List));
                p->data=x;
                p->next=L->next;   //注意p->next一定是L->next,不能是NULL,否则会丢失之前插入的节点
                L->next=p;
                cout<<"输入节点数据\n";
                cin>>x;
            }
            return L;
        }

    /*尾插法*/
        list f_endinsert(list &L){
             L=(list)malloc(sizeof(List));
            L->next=NULL;
            list m=L;
            ElemType x;
            cout<<"\n输入节点数据,-1表示结束输入:\n";
            cin>>x;
             while(x!=-1){
                list p=(list)malloc(sizeof(List));
                p->data=x;
                p->next=NULL;   //注意p->next一定是L->next,不能是NULL,否则会丢失之前插入的节点
                m->next=p;
                m=p;
                cout<<"输入节点数据\n";
                cin>>x;
            }
            return L;
        }

/*遍历链表*/
void fs_bl(list &L){
    while(L->next!=NULL){
    cout<<L->next->data<<"->";
    L=L->next;
    if(L->next==NULL){
        cout<<"NULL";
        }
    }
}

/*主函数*/
int main()
{
   list l;
   f_initialize(l);
   l=f_headinsert(l);
   fs_bl(l);
  l=f_endinsert(l);
   fs_bl(l);
    return 0;
}

希望对大家有用哦!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瓷瓷的可可

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值