介绍
本文介绍了使用C++实现单链表的基本操作,包括尾部插入、尾部删除、头部插入和头部删除。单链表是一种基本的数据结构,掌握了这些基本操作对于初学者来说非常重要。
代码实现
#include<iostream>
using namespace std;
// 定义单链表节点结构体
typedef int SLTDateType;
typedef struct SListNode
{
SLTDateType data;
SListNode* next;
}SListNode;
// 申请单链表节点
SListNode* BuySListNode(SLTDateType x)
{
SListNode* newnode = new SListNode;
if (newnode == NULL)
{
cout << "申请失败\n";
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
return newnode;
}
// 尾部插入节点
void SLTPushBack(SListNode** phead, SLTDateType x)
{
SListNode* newNode = BuySListNode(x);
if (*phead == NULL)
{
*phead = newNode;
}
else
{
SListNode* tail = *phead;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newNode;
}
}
// 尾部删除节点
void SLTPopBack(SListNode** phead)
{
if (*phead == NULL)
{
return;
}
else if ((*phead)->next == NULL)
{
free(*phead);
*phead = NULL;
}
else {
SListNode* prev = NULL;
SListNode* tail = *phead;
while (tail->next != NULL)
{
prev = tail;
tail = tail->next;
}
delete tail;
tail = NULL;
prev->next = NULL;
}
}
// 头部插入节点
void SLTPushFront(SListNode** phead, SLTDateType x)
{
SListNode* newNode = BuySListNode(x);
newNode->next = *phead;
*phead = newNode;
}
// 头部删除节点
void SLTPopFront(SListNode** phead)
{
if (*phead == NULL)
{
return;
}
else
{
SListNode* next = (*phead)->next;
delete *phead;
*phead = next;
}
}
// 打印链表
void SLTPrint(SListNode* phead)
{
SListNode* cur = phead;
while (cur != NULL)
{
printf("%d", cur->data);
if (cur->next != NULL)
{
printf(" -> ");
}
cur = cur->next;
}
}
int main()
{
SListNode* head = NULL;
SLTPushBack(&head, 1);
SLTPushBack(&head, 2);
SLTPushBack(&head, 3);
SLTPushBack(&head, 4);
SLTPushFront(&head, 10);
SLTPushFront(&head, 20);
SLTPopFront(&head);
SLTPushFront(&head, 30);
SLTPopFront(&head);
SLTPopFront(&head);
SLTPopFront(&head);
SLTPopFront(&head);
SLTPopFront(&head);
SLTPopFront(&head);
SLTPopFront(&head);
SLTPrint(head);
return 0;
}