#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;
}
删除单链表中指定的节点
最新推荐文章于 2024-06-29 01:13:46 发布