C++实现链表及其应用


#include <iostream>
using namespace std;


//链表节点
typedef struct node {
	int data;
	node *next;
}node;

//初始化
void Inite(node* listedsq) {
	listedsq->data = 0;
	listedsq->next = NULL;
}
//插入节点(头插)
bool Inserthead(node *head, int value) {
	node *s = new node;
	s->data = value;
	s->next = head->next;
	head->next = s;
	return true;
}
//插入节点(尾插)
bool Insertend(node *head, int value) {
	node *temp = new node;
	node *s = head;
	temp->data = value;
	temp->next = NULL;
	while (s->next != NULL) {
		s = s->next;
	}
	s->next = temp;
	return true;
}

//删除指定序号的元素
bool Delete(node *head, int pos) {
	if (head->next == NULL) {
		cout << "表为空,无法删除" << endl;
		return false;
	}
	node *s = head;
	node *temp;
	for (int i = 1; i < pos;i++) {
		if (s->next == NULL) {
			cout << "超出链表长度,删除失败!" << endl;
			return false;
		}
		s = s->next;
	}
	temp = s->next;
	s->next = s->next->next;
	delete temp;
	return true;
}

//按表节点查找值
int Getvalue(node *head, int pos) {
	node *temp = head->next;
	for (int i = 1; i < pos; i++) {
		temp = temp->next;
		if (temp == NULL) {
			cout << "查找位置超过链表长度" << endl;
			return NULL;
		}
	}
	return temp->data;
}

//输出所有元素
void Output(node *head) {
	node *temp;
	temp = head->next;
	while (temp != NULL) {
		cout << temp->data << ",";
		temp = temp->next;
	}
	cout << endl;
}

int main() {
	//定义链表
	cout << "链表" << endl;
	node* l = new node;
	Inite(l);//初始化
	cout << endl;

	//插入10个数
	cout << "插入10个数:" << endl;
	for (int i = 1; i < 11; i++) {
		Insertend(l, i);

	}
	Output(l);//输出链表的所有元素
	cout << endl;

	cout << "删除链表的第3、5个元素:" << endl;
	Delete(l, 3);//删除链表的第3个元素
	Delete(l, 5);
	Output(l);
	cout << endl;


	cout << "输出链表的第5个元素值:" << endl;
	cout << Getvalue(l, 5) << endl;//输出链表的第5个元素值
	cout << "输出链表的第10个元素值:" << endl;
	cout << Getvalue(l, 10) << endl;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值