单链表的创建、增加、删除、倒转
//链表
typedef struct Node
{
int data;
struct Node *next;
}TyLIST;
//1.创建链表
TyLIST *CreateList()
{
TyLIST *m_pHead = (TyLIST *)malloc(sizeof(TyLIST));
m_pHead->data = 0;
m_pHead->next = nullptr;
int m_nvalue = 0;
printf("请输入数字(-1:退出):");
scanf("%d",&m_nvalue);
TyLIST *m_pCur = m_pHead;
while (m_nvalue != -1)
{
TyLIST *m_pM = (TyLIST *)malloc(sizeof(TyLIST));
m_pM->data = m_nvalue;
m_pM->next = nullptr;
m_pCur->next = m_pM;
printf("请输入数字(-1:退出):");
scanf("%d", &m_nvalue);
m_pCur = m_pM;
}
return m_pHead;
}
//2.打印链表
void PrintList(TyLIST *m_Phead)
{
printf("--------------------------\n");
TyLIST *m_pCur = m_Phead->next;
while (m_pCur)
{
printf("%d ",m_pCur->data);
m_pCur = m_pCur->next;
}
printf("\n--------------------------\n");
}
//3.销毁链表
void DestoryList(TyLIST *m_Phead)
{
TyLIST *temp = nullptr;
while (m_Phead)
{
//缓存后继结点位置
temp = m_Phead->next;
free(m_Phead);
m_Phead = nullptr;
//指针后移
m_Phead = temp;
}
}
//4.按值插入元素,在某一元素前
void InSertNode(TyLIST *m_Phead, int m_x, int m_y)
{
if (!m_Phead)
{
return;
}
TyLIST *m_pCur = m_Phead->next;
TyLIST *m_pPre = m_Phead;
while (m_pCur)
{
if (m_x == m_pCur->data)
{
break;
}
m_pPre = m_pCur;
m_pCur = m_pCur->next;
}
TyLIST *m_pNew = (TyLIST *)malloc(sizeof(TyLIST ));
m_pNew->data = m_y;
m_pNew->next = m_pCur;
m_pPre->next = m_pNew;
}
//5.按值删除元素
void DelNodeByValue(TyLIST *m_pHead, int m_nvalue)
{
TyLIST *m_pCur = m_pHead->next;
TyLIST *m_pPre = m_pHead;
while (m_pCur->next)
{
if (m_nvalue == m_pCur->data)
{
break;
}
m_pPre = m_pCur;
m_pCur = m_pCur->next;
}
m_pPre->next = m_pCur->next;
free(m_pCur);
m_pCur = NULL;
}
//6.链表逆置
void ReverseList(TyLIST *m_phead)
{
if (nullptr == m_phead || nullptr == m_phead->next || nullptr == m_phead->next->next)
{
return;
}
TyLIST *m_pPre = m_phead->next;
TyLIST *m_pCur = m_phead->next->next;
TyLIST *m_next = nullptr;
while (m_pCur)
{
//1.缓存下一节点
m_next = m_pCur->next;
//2.重新连接
m_pCur->next = m_pPre;
//3.m_pPre,m_pCur下移
m_pPre = m_pCur;
m_pCur = m_next;
}
//4.让尾节点为NULL
m_phead->next->next = nullptr;
//5.头节点重新指向
m_phead->next = m_pPre;
}
void main()
{
TyLIST *m_phead = CreateList();
PrintList(m_phead);
InSertNode(m_phead,30, 29);
PrintList(m_phead);
DelNodeByValue(m_phead, 29);
PrintList(m_phead);
ReverseList(m_phead);
PrintList(m_phead);
DestoryList(m_phead);
system("pause");
}
结果: