C语言单向链表的反转实现

#include <stdio.h>
#include <stdlib.h>

typedef struct  node
{
    int value;
    struct node *next;
} nodes;

nodes *LinkList_Init();
void Insert_value(int value_in, nodes *P_node);
void Insert_pos_value(int value_in, int pos, nodes *p_node);
void Foreach_Linklist(nodes * p_node);
void Reserve_LinkList(nodes *p_node);

int main() {
    printf("---开始创建链表---\n");
    nodes* p_head = LinkList_Init();
    printf("---链表创建完毕---\n");
    
    printf("---开始后插数据--\n");
    Insert_value(1, p_head);
    Insert_value(2, p_head);
    Insert_value(3, p_head);
    Insert_value(4, p_head);
    Insert_value(5, p_head);
    Insert_value(6, p_head);
    printf("---后插数据完毕---\n");
    Foreach_Linklist(p_head);

    printf("---开始反转链表--\n");
    Reserve_LinkList(p_head);
    printf("---反转链表完毕---\n");
    Foreach_Linklist(p_head);
    system("pause");
    return 0;
}

//链表初始化
nodes *LinkList_Init() {
    nodes *p_node = (nodes*)malloc(sizeof(nodes));
    p_node -> next = NULL;
    return p_node;
}

//往后插入数据
void Insert_value(int value_in, nodes *P_node) {
    if(P_node == NULL)
        return;
    nodes *p_current = P_node;
    nodes *new_node = (nodes*)malloc(sizeof(nodes));
    new_node -> value = value_in;
    new_node -> next = NULL;
    while(p_current -> next != NULL) {
        p_current = p_current -> next;
    }
    p_current -> next = new_node;
}

//遍历链表
void Foreach_Linklist(nodes *p_node) {
    if(p_node == NULL)
        return;
    nodes * p_current = p_node -> next;
    while(p_current != NULL) {
        printf("%d\n", p_current -> value);
        p_current = p_current -> next;
    }
}

//链表反转
void Reserve_LinkList(nodes *p_node) {
    if(p_node == NULL)
        return;
    nodes *p_privious = p_node -> next;
    nodes *p_current = p_privious -> next;
    p_privious -> next = NULL;//链表尾置空
    if(p_current == NULL || p_privious == NULL)
        return;
    while(p_current != NULL) {
        nodes *p_next = p_current -> next;
        p_current -> next = p_privious;
        p_privious = p_current;
        p_current = p_next;
    }
    p_node -> next = p_privious;//链表头重新指向
}
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值