view plaincopy to clipboardprint?#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;
}
作者“wangyangkobe的專欄”