#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
#include<stdbool.h>
typedef int SListDataType;
typedef struct SListNode{
SListDataType date;
struct SListNode* next;
}SListNode;
SListNode* SListInit(SListNode* phead);//初始化
SListNode* SListBuyNode(SListDataType x);//增加一个节点
void SListPushBack(SListNode* phead, SListDataType x);//尾增
void SListPopBack(SListNode* phead);//尾删
void SListPushfrot(SListNode* phead, SListDataType x);//头增
void SListPopfrot(SListNode* phead);//头删
void SListPrint(SListNode* phead);//打印链表
SListNode* SListFind(SListNode* phead, SListDataType x);//查找
void reversList1(SListNode* phead);// 反转链表
SListNode* SListInit(SListNode* phead)//初始化
{
phead->date = 0;
phead->next = NULL;
}
SListNode* SListBuyNode(SListDataType x)//增加一个节点
{
SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
newnode->date = x;
newnode->next = NULL;
return newnode;
}
void SListPushBack(SListNode* phead, SListDataType x)//尾增
{
assert(phead);
SListNode* newnode = SListBuyNode(x);
if(phead->next==NULL)
{
phead->next = newnode;
}
else{
SListNode* cur = phead;
while(cur->next != NULL){
cur = cur->next;
}
cur->next = newnode;
}
}
void SListPrint(SListNode* phead)//打印链表
{
assert(phead);
if(phead->next == NULL){
printf("0\n");
}
else{
SListNode* cur = phead->next;
while(cur)
{
printf("%d->",cur->date);
cur = cur->next;
}
}
printf("NULL");
}
void SListPopBack(SListNode* phead)//尾删
{
assert(phead);
SListNode* cur = phead->next;
SListNode* prev = NULL;
if(phead->next == NULL){
return;
}
else{
while(cur->next != NULL)
{
prev = cur;
cur = cur->next;
}
free(cur);
prev->next = NULL;
}
}
void SListPushfrot(SListNode* phead, SListDataType x)//头增
{
assert(phead);
SListNode* newnode = SListBuyNode(x);
if(phead->next == NULL){
phead->next = newnode;
}
else{
newnode->next = phead->next;
phead->next = newnode;
}
}
void SListPopfrot(SListNode* phead)//头删
{
assert(phead);
if(phead->next == NULL)
{
return;
}
SListNode* cur = phead->next;
if(cur->next == NULL){
free(cur);
phead->next = NULL;
}
else{
SListNode* Ne = cur->next;
phead->next = Ne;
free(cur);
}
}
SListNode* SListFind(SListNode* phead, SListDataType x)//查找
{
assert(phead);
SListNode* cur = phead->next;
while(cur)
{
if(cur->date == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
void reversList1(SListNode* phead)// 反转链表
{
assert(phead);
if(phead == NULL || phead->next == NULL)
{
return;
}
else
{
SListNode* n1 = NULL;
SListNode* n2 = phead->next;
SListNode* n3 = phead->next->next;
while(n2)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if(n3)
{
n3 = n3->next;
}
}
phead->next = n1;
}
}
int main()
{
SListNode head;
SListInit(&head);
SListPushBack(&head,1);
SListPushBack(&head,2);
SListPushBack(&head,3);
SListPushBack(&head,4);
SListPushBack(&head,5);
SListPushBack(&head,6);
//SListPopBack(&head);
//SListPushfrot(&head, 0);
//SListPopfrot(&head);
//SListNode* It = SListFind(&head, 5);
reversList1(&head);
SListPrint(&head);
return 0;
}
单链表(代码)
于 2024-06-24 11:06:56 首次发布