#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