链表插入删除操作

#include <iostream>
using namespace std;
// 定义单向链表节点
struct ListNode
{
	int data;
	ListNode* next;
}; // end of ListNode
// 将新节点插入链表头
void insertList(ListNode** head, int insertData)
{
	if(head == NULL)
	{
		return;
	}
	ListNode* pNode = new ListNode;
	pNode->data = insertData;
	pNode->next = *head;
	*head = pNode;
}
// 删除链表中的节点
void removeList(ListNode** head, int removeData)
{
	if(head == NULL || *head == NULL)
	{
		return;
	}
	ListNode* pre = NULL; // 指向当前节点的前一个节点
	ListNode* cur = *head;
	for(; cur != NULL && cur->data != removeData; pre = cur, cur = cur->next)
	{
	}
	// 找到相应节点
	if(cur != NULL)
	{
		// 要删除的节点是头节点
		if(pre == NULL)
		{
			*head = cur->next;
		}
		else // 非头节点
		{
			pre->next = cur->next;
		}
		delete cur;
	}
}
// 显示链表
void showList(const ListNode* head)
{
	for(const ListNode* p = head; p != NULL; p = p->next)
	{
		cout << p->data << '\t';
	}
	cout << endl;
}
int main(int argc, char* argv[])
{
	int arr[] = {4, 3, 2, 1};
	int size = sizeof(arr) / sizeof(int);
	ListNode* head = NULL;
	for(int i = 0; i < size; ++i)
	{
		insertList(&head, arr[i]);
	}
	showList(head);
	// 当前节点序列(1 2 3 4)
	// 删除中间节点
	removeList(&head, 2);
	showList(head);
	// 删除头节点
	removeList(&head, 1);
	showList(head);
	// 删除尾节点
	removeList(&head, 4);
	showList(head);
	// 删除最后一个节点
	removeList(&head, 3);
	showList(head);
}

运行结果:

1 2 3 4
1 3 4
3 4
3



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值