数据结构c/c++ 头插法尾插法建立带头结点的单链表,以数组创建带头结点的单链表和不带头结点的单链表,输出打印单链表

//
// Created by 焦娇 on 2021/9/17.
//

#ifndef CHAPTER2_LINELINK_LLK_H
#define CHAPTER2_LINELINK_LLK_H

#endif //CHAPTER2_LINELINK_LLK_H
#include <iostream>

using namespace std;
typedef int Elemtype;
typedef struct LNode {
    Elemtype data;              //数据域
    struct LNode *next;         //指针域,指向后继
}LNode, *LinkList;              //LinkList 等价于 LNode*

//以数组建立 不带头结点的单链表,(单链表,元素个数,数组传入)
LinkList CreatListByArray(LinkList &L,int n,int a[n]){
    int i = 0;
    L = (LinkList) malloc(sizeof(LNode));
    LNode *s;
    L->next = NULL;
    LNode *r = L;
    L->data = a[0];
    for (i = 1; i < n; i++) {
        s = (LinkList) malloc(sizeof(LNode));
        s->data = a[i];
        r->next = s;
        s->next = NULL;
        r = s;
    }
}
//以数组建立 带头结点的单链表
LinkList CreatLListByArray(LinkList &L,int n,int a[n]){
    int i = 0;
    L = (LinkList) malloc(sizeof(LNode));
    LNode *s;
    L->next = NULL;
    LNode *r = L;
    L->data = 0;
    for (i = 0; i < n; i++) {
        s = (LinkList) malloc(sizeof(LNode));
        s->data = a[i];
        r->next = s;
        s->next = NULL;
        r = s;
    }
}
//带头结点 头插法
LinkList CreatListByHead(LinkList &L){
    LNode *s;
    int x;
    L = (LinkList)malloc(sizeof (LNode));
    L->next = NULL;
    cout<<"请输入需要创建的链表,以 9999 为结束:";
    cin>>x;
    while (x!=9999){
        s = (LinkList)malloc(sizeof (LNode));
        s->data = x;
        s->next = L->next;
        L->next = s;

        cin>>x;
    }
    return L;
}
//带头结点 尾插法
LinkList CreatListByTail(LinkList &L){
    int x;
    L = (LinkList)malloc(sizeof (LNode));
    LNode *s;
    LNode *r = L;
    cout<<"请输入需要创建的链表,以 9999 为结束:";
    cin>>x;

    while (x!=9999){
        s = (LinkList)malloc(sizeof (LNode));
        s->data = x;

        r->next = s;
        r = s;
        cin>>x;
    }
    r->next = NULL;
    return L;
}
//输出不带头结点的 单链表
void PrintLinkListwithoutL(LinkList &L){
    cout<<"单链表为:"<<endl;
    for(LinkList I = L;I!=NULL;I=I->next){
        cout<<I->data<<"->";
    }
    cout<<"Null";
}
//输出带头结点的 单链表
void PrintLinkListwithL(LinkList &L){
    cout<<"单链表为:"<<endl;
    for(LinkList I = L->next;I!=NULL;I=I->next){
        cout<<I->data<<"->";
    }
    cout<<"Null";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值