C++链表的创建及操作

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。

一、链表定义与函数声明

首先,本文主要将链表的操作分为三个部分,即创建链表,删除节点以及增加节点。其中链表的结构体定义以及函数声明与主函数如下:

typedef struct ListNode {
	double value;
	ListNode* next;
}ListNode;

ListNode* CreateList();
ListNode* DeleteNode(ListNode*);
ListNode* InsertNode(ListNode*);

二、链表创建

创建头结点,并根据输入内容增加节点值。
提示:需要注意的是,此处使用while (cin>>Inputnum)作为循环判断条件,在函数最后必须清除cin缓冲区以继续后续输入。

ListNode* CreateList() {
	cout << "Input ListNode:" << endl;
	int Inputnum ;
	ListNode* head, * nodetemp, * node;
	head = nullptr;
	nodetemp = nullptr;

	while (cin>>Inputnum)
	{
		node = new ListNode;
		node->value = Inputnum;
		if (head == nullptr) {
			head = node;
		}
		else{
			nodetemp->next = node;
		}
		nodetemp = node;
		nodetemp->next = nullptr;
	}
	cin.clear();
	cin.ignore();
	return head;
}

三、删除节点

链表的节点删除包含指针操作,以防断链。

ListNode* DeleteNode(ListNode* head) {
	int locate;
	cout << "Input delete location: " << endl;
	cin >> locate;
	if (locate == 1) {
		head = head->next;
	}
	else {
		ListNode* temp;
		temp = head;
		for (int i = 1; i < locate-1; i++) {
			temp = temp->next;
		}
		temp->next = temp->next->next;
	}
	return head;
}

四、插入节点

节点的插入同样包含指针操作,同时要判断插入位置的合法性。

ListNode* InsertNode(ListNode* head) {
	int locate;
	ListNode* insertnode = new ListNode;
	insertnode->next = nullptr;
	cout << "Input insert location: " << endl;
	cin >> locate;
	cout << "Input insert node: " << endl;
	cin >> insertnode->value;
	if (locate == 1) {
		insertnode->next = head;
		head = insertnode;
	}
	else {
		ListNode* temp;
		temp = head;
		for (int i = 1; i < locate - 1; i++) {
			temp = temp->next;
		}
		if (temp==nullptr) {
			cout << "illegal location!" << endl;
			exit(0);
		}
		else if (temp->next == nullptr) {
			temp->next = insertnode;
		}
		else {
			insertnode->next = temp->next;
			temp->next = insertnode;
		}

	}
	return head;
}

总结

最后,函数的主体与链表的打印。

int main() {
	
	ListNode* head, *count;


	head = CreateList();
	PrintList(head);
	head = DeleteNode(head);
	PrintList(head);
	head = InsertNode(head);
	PrintList(head);

	return EXIT_SUCCESS;
}


void PrintList(ListNode* head) {
	ListNode* count;
	count = head;
	while (count != nullptr) {
		cout << count->value << " ";
		count = count->next;
	}
	cout << endl;
}
  • 25
    点赞
  • 151
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值