链表操作—头插法尾插法

单链表的插入操作,包括头插和尾插,两种的时间复杂度都为O(n)。

/*
	单链表插入操作(头插+尾插)
*/
#include<iostream>
#include<malloc.h>
using namespace std;
//定义结点数据类型
typedef int Elemtype;

//结点定义
typedef struct LNode {
	Elemtype data;
	LNode* next;
}LNode, * Linklist;

//单链表的初始化
Linklist initList() {
	Linklist L;
	L = (Linklist)malloc(sizeof(LNode));
	L->next = NULL;
	return L;
}
//头插法
void headInsert(Linklist& L) {
	Linklist p;
	p = (Linklist)malloc(sizeof(LNode));
	cout << "输入链表的数据,-1表示结束" << endl;
	cin >> p->data;
	while (p -> data != -1) {
		p->next = L->next;
		L->next = p;
		p = (Linklist)malloc(sizeof(LNode));
		cin >> p->data;
	}
}

//尾插法
void tailInsert(Linklist &L) {
	Linklist p,end;//end表示尾指针
	end = L;
	p = (Linklist)malloc(sizeof(LNode));
	cout << "输入链表的数据,-1表示结束" << endl;
	cin >> p->data;
	while (p->data != -1) {
		p->next = end->next;
		end->next = p;
		end = p;//尾指针向后移
		p = (Linklist)malloc(sizeof(LNode));//重新分配内存
		cin >> p->data;//继续增加结点
	}
	end->next = NULL;
}

//打印链表
void printList(Linklist& L) {
	Linklist p;
	p = L->next;
	while (p) {
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
}
int main()
{
	Linklist L = initList();
	cout << "选择创建单链表方式:1.头插法  2.尾插法" << endl;
	int s;
	cin >> s;
	if (s == 1) {
		headInsert(L);
		cout << "头插法创建出的链表为:";
		printList(L);
	}
	else if (s == 2) {
		tailInsert(L);
		cout << "尾插法创建出的链表为:";
		printList(L);
	}
	else {
		cout << "出错" << endl;
	}
	return 0;
}

运行结果
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Gtl722

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

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

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

打赏作者

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

抵扣说明:

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

余额充值