//
// 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";
}
数据结构c/c++ 头插法尾插法建立带头结点的单链表,以数组创建带头结点的单链表和不带头结点的单链表,输出打印单链表
最新推荐文章于 2022-11-16 22:53:05 发布