删除单链表中指定的节点

#include "stdafx.h"
#include <string>
#include <iostream>
#include <cassert>
using namespace std; 

struct Node
{
	int pos;
	Node *pNext;
	Node(int position = -1, Node *next = NULL)
		:pos(position), pNext(next){}
};
//创建单链表
Node *CreateSingleList(int arr[], int n)
{
	Node *head = new Node;
	Node *createNode = NULL;
	Node *temp = head;
	for (int i = 0; i < n; ++i)
	{
		createNode = new Node(arr[i]);
		temp->pNext = createNode;
		temp = createNode;
	}
	return head;
}
//输出单链表
void Print(Node *head)
{
	while (head->pNext != NULL)
	{
		cout<<head->pNext->pos<<" ";
		head = head->pNext;
	}
	cout<<endl;
}

//查找元素值为target的节点
Node *FindNode(Node *head, int target)
{
	Node *res = NULL;
	while (head->pNext != NULL)
	{
		if (head->pNext->pos == target)
		{
			return head->pNext;
		}
		head = head->pNext;
	}
	return res;
}
//删除指定元素值为target的节点
void RemoveNode(Node *&head, int target)
{
	//找到节点target的前驱节点
	Node *curr = head->pNext;
	Node *pre = head;
	while (curr != NULL )
	{
		if (curr->pos == target)
		{
			break;
		}
		else
		{
			pre = curr;
			curr = curr->pNext;
		}
	}

	//删除节点
	pre->pNext = curr->pNext;
	curr->pNext = NULL;
}
int main()
{
	const int N = 10;
	int arr[N];

	for (int i = 0; i < N; ++i)
	{
		arr[i] = i + 1;
	}

	Node *head = CreateSingleList(arr, N);

	Node *res = FindNode(head, 5);
	cout<<"Find node :"<<res->pos<<endl;

	cout<<"单链表为:";
	Print(head);
	cout<<endl;

	RemoveNode(head, 1);
	cout<<"删除后为:";
	Print(head);
	cout<<endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值