学习目标:
- 单链表的设计和实现
学习内容:
一、单链表头文件
//不带头单向非循环链表
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
//链表是由结点组成,而结点由数据域和地址域构成。最后一个结点的地址域为NULL
typedef int SLDataType;
typedef struct SListNode
{
//数据域
SLDataType data;
//地址域:保存了下一个结构体(结点)的地址
struct SListNode* next;//struct SListNode next;这种是错误的,结构体里面不能定义自己类型的结构体变量。但可以定义结构体指针
//cur是当前节点,cur->next既是当前结点的指针域数据,也是下一个结点
}SListNode;
//typedef struct SListNode SListNode;
//遍历打印链表
void SListPrint(SListNode* phead);
//尾插
void SListPushBack(SListNode** pphead, SLDataType x);
//尾删
void SListPopBack(SListNode** phead);
//头插
void SListPushFront(SListNode** pphead, SLDataType x);
//头删
void SListPopFront(SListNode** pphead);
//单链表查找
SListNode* SListFind(SListNode* phead, SLDataType x);
//在pos指针的前面插入x
void SListInsertBefore(SListNode** pphead, SListNode* pos, SLDataType x);
//删除pos指针位置的值
void SListErase(SListNode** pphead, SListNode* pos);
//在pos指针的后面插入x
void SListInsertAfter(SListNode* pos, SLDataType x);
//删除pos指针后面的值
void SListEraseAfter(SListNode* pos);
//释放链表
void SListDestory(SListNode** pphead);
注意:
结构体里面不能定义自己类型的结构体变量。但可以定义结构体指针。
cur是当前节点,cur->next既是当前结点的指针域数据,也是下一个结点。
二、代码实现
1、void SListPrint(SListNode* phead);遍历打印链表
void SListPrint(SListNode* phead)
{
//assert(phead);//这里不能加断言,否则空链表不能打印
SListNode* cur = phead;
while (cur != NULL)//cur等于空,表示头地址没有链表,循环结束
{
//循环写的是继续的条件,想的是结束的条件
printf("%d-> ", cur->data);
//改变指针,指向下一个结点
cur = cur->next;//cur->next既是当前结点的指针域数据,也是下一个结点
}
printf("NULL\n");
}
注意:cur是当前节点,cur->next既是当前结点的指针域数据,也是下一个结点。
2、void SListPushBack(SListNode** pphead, SLDataType x);尾插
找到尾节点的指针,找到后,赋值一个malloc(sizeof(slnode))地址。
//传值调用:
void SListPushBack(SListNode* phead, SLDataType x)
{
SListNode* newNode = (SListNode*)malloc(sizeof(SListNode));
//判断开辟空间是否成功
if (newNode == NULL)
{
printf("申请结点失败\n");
exit(-1);
}
newNode->data = x;
newNode->next = NULL;
SListNode* tail = phead;
while (tail != NULL)//找到了,则tail为NULL,循环结束
{
tail = tail->next;
}
//链接
tail->next = newNode;
//思考:该程序是否有问题
//tail为空时,即phead==NULL,解引用报错
}
void SListPushBack(SListNode* phead, SLDataType x)
{
//将地址作为值传递,phead改变,但不会影响pList
SListNode* newNode = (SListNode*)malloc(sizeof(SListNode));
//判断开辟空间是否成功
if (newNode == NULL)
{
printf("申请结点失败\n");
exit(-1);
}
newNode->data = x;
newNode->next = NULL;
if (phead == NULL)//空链表,一上来就解引用操作,会导致问题
{
//当为空链表时,创建一个空间,链接上去
SListNode* phead = newNode;
}
else
{
SListNode* tail = phead;
//找到尾节点的指针。
while (tail->next != NULL)//如果没有判断phead为NULL,则空链表直接解引用错误
{
tail = tail->next;
}
//tail->next为空,tail不为空,为最后一个节点
//链接
tail->next