[C++]单链表的相关操作(v1.0版-继续补充)

材料天坑选手跨考408。。。。今天复习单链表,在VS上把单链表的一些操作写成了头文件singlyLinkList.h,因为还有其他学习任务,今天就码了一部分,代码如下:

注:所有操作都是针对带头结点的单链表

//定义单链表结点
struct LNode {
	int data;
	LNode* next;
};

今天实现的功能有: 

frontInsert在给定指针p后面插入结点
behindInsert/在给定指针p前面插入结点
head_insert头插法函数,初始链表为空
tail_insert尾插法函数tail_insert,手动输入,初始链表为空
auto_assignment

给空表自动赋值auto_assignment

printList遍历单链表
emptyList判空函数

代码如下:

#include<iostream>
using namespace std;

#define MAX 25
//带头结点的单链表操作

//定义单链表结点
struct LNode {
	int data;
	LNode* next;
};
//在给定指针p后面插入结点
bool frontInsert(LNode* p,int e) {
	LNode *s = (LNode*)malloc(sizeof(LNode));
	if (s == NULL)return false;

	s->data = p->data;
	s->next = p->next;
	p->next = s;
	p->data = e;

	return true;
}

//在给定指针p前面插入结点
bool behindInsert(LNode* p,int e) {

	LNode *s = (LNode*)malloc(sizeof(LNode));
	if (s == NULL)return false;
	s->data = e;
	//两步插入节点
	s->next = p->next;
	p->next = s;
	return true;
}

//头插法函数,初始链表为空
bool head_insert(LNode* L) {
	L->next = NULL;
	LNode* s;
	int x;
	while (1) {
		cin >> x;
		if (x == -1)break;
		s = (LNode*)malloc(sizeof(LNode));
		if (s == NULL  )return false;
		s->next = L->next;
		L->next = s;
		s->data = x;
	}
	return true;
}
//尾插法函数tail_insert,手动输入,初始链表为空
bool tail_insert(LNode* L) {
	L->next = NULL;
	int x=0;
	LNode *s = L;//s指向最后一个节点
	while (1) {//输入-1结束插入操作
		cin >> x;
		if (x == -1)break;
		s->next = (LNode*)malloc(sizeof(LNode));
		if (s == NULL)return false;
		s->next->data = x;
		s->next->next = NULL;
		s = s->next;
	}
	return true;
}
//给空表自动赋值auto_assignment
//单链表L,num表示自动尾插的节点个数
bool auto_assignment(LNode* L, int num=20) {
	if (num<1||num > MAX||L->next!=NULL) return false;
	LNode *s = L;//s指向最后一个节点

	for (int i = 0; i < num;i++) {
		s->next = (LNode*)malloc(sizeof(LNode));
		s->next->next = NULL;
		s->next->data = rand() % 100;
		s = s->next;
	}
	return true;
}
//遍历函数printList
bool printList(const LNode* L) {
	if (L->next == NULL)return false;
	LNode*s = L->next;
	int i = 0;
	while(s!=NULL) {
		cout << s->data << " " ;
		s = s->next;
		if (i % 10 == 9)cout << endl;
		i++;
	}
	cout << endl;
	return true;
}

//判空函数
bool emptyList(const LNode* L) {
	if (L->next == NULL) {
		return true;
	}
	return false;
}

欢迎批评指正!

点滴努力,汇聚成海,加油!

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值