单链表逆序

逆序原理:保留头节点下一个结点地址,将头节点断开,遍历除头节点以外的节点,将那些节点头插入头节点中。就能实习逆序。

/*******************************************************************
*
*	file name:	demo2.c
*	author	 :  lzj
*	date	 :  2024/04/23
*	function :  单向链表倒序
* 	note	 :  None
*
*	CopyRight (c)  2023-2024   jjh6lzj@163.com   All Right Reseverd 
*
* *****************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int DataType;
//定义结构体
typedef struct cricSeqlist
{
    DataType data;
    struct cricSeqlist *next;
}criSeL;
//逆序

void nixu2(criSeL *Head)
{
    criSeL *p=Head->next;
    while (p!=NULL)
    {
        criSeL *tem=p->next;
        p->next=Head->next;
        Head->next=p;
        p=tem;
    }
    
}
//创建头节点
criSeL * InitcriSwl()
{
    criSeL *Head=(criSeL *)calloc(1,sizeof(criSeL));
    if (Head==NULL)
    {
        perror("Head Node creat fail");
        exit(-1);
    }
    Head->next=NULL;
    return Head;
}
//创建新节点
criSeL * CreatNode(DataType data)
{
    criSeL *NewNode=(criSeL *)calloc(1,sizeof(criSeL));
    if (NewNode==NULL)
    {
        perror("Head Node creat fail");
        exit(-1);
    }
    NewNode->data=data;
    NewNode->next=NULL;
    return NewNode;
}
//头插入节点
bool InsertNode(criSeL *Head,DataType data)
{
    criSeL *node=CreatNode(data);
    if (Head==NULL)
    {
        return false;
    }
    if (Head->next==NULL)
    {
        Head->next=node;
        node->next=NULL;
        return true;
    }
    node->next=Head->next;
    Head->next=node;
    return true;
}
//头删除
bool HeadRemove(criSeL *Head)
{
    if (Head->next==NULL)
    {
        return false;
    }
    criSeL *lasNode=Head->next;
    Head->next=Head->next->next;
    lasNode->next=NULL;
    free(lasNode);
    return true;
}
//遍历
void prin(criSeL *Head)
{
    if (Head->next==NULL)
    {
        return;
    }
    criSeL *pHead=Head;
    while (pHead->next!=NULL)
    {
        pHead=pHead->next;
        printf("%d\n",pHead->data);
    }
}
//单链表逆序
void nixu(criSeL *Head)
{
    if (Head->next==NULL)return;
    criSeL *p=Head->next;
    Head->next=NULL;
    while(p!=NULL)
    {
        if (Head->next==NULL)
        {
            Head->next=p;
            p=p->next;
            Head->next->next=NULL;
            continue;
        }
        criSeL *tem=p->next;
        p->next=Head->next;
        Head->next=p;
        p=tem;
    }
}
int main()
{
    criSeL *p=InitcriSwl();
    InsertNode(p,7);
    InsertNode(p,8);
    InsertNode(p,9);
    nixu(p);
    prin(p);
    return 0;
}
posted @ 2024-05-06 21:10  夏雪呦  阅读(24)  评论(0)    收藏  举报