链表反向 node_reverse()

假设链表为:1 2 3 4

现在需要把链表反向,变为:4 3 2 1

利用迭代法:

void node_reverse(Node** head)
{
    Node* p_prev = NULL;
    Node* p_curr = *head;
    Node* p_next = NULL;
    while (p_curr != NULL) {
        p_next = p_curr->next;
        p_curr->next = p_prev;
        p_prev = p_curr;
        p_curr = p_next;
    }
    *head = p_prev;
}

首先:假设各个节点地址为 150、200、125、100

那么最开始数据形式如下图

while()第一次运行完成后:变成下图

while()第二次运行完成后:变成下图

while()第三次运行完成后:变成下图

while()第四次运行完成后:变成下图 退出循环

最后把头结点指向p_prev,变成下图

即:

添加Node 定义、node_add()、node_print()

//node.h
#ifndef _NODE_H_
#define _NODE_H_

typedef struct Node
{
    int data;
    struct Node* next;
}Node;

/**
 * @brief 链表添加数据,尾插法
 * @param[in] head 链表
 * @param[in] data 需要添加的数据
 * @param[out] 1 :添加成功 0:添加失败
*/
int node_add(Node **head, int data);

/**
 * @brief 链表遍历
 * @param[in] head 链表
*/
void node_print(Node *head);

/**
 * @brief 链表遍历
 * @param[in] head 链表
*/
void node_reverse(Node** head);
#endif /* ! _NODE_H_ */
//node.c
#include <stdlib.h>
#include <stdio.h>
#include "node.h"

/**
 * @brief 链表添加数据,尾插法
 * @param[in] head 链表
 * @param[in] data 需要添加的数据
 * @param[out] 1 :添加成功 0:添加失败
*/
int node_add(Node **head, int data)
{
    Node* temp = (Node*)malloc(sizeof(Node));
    if (temp == NULL) {
        return NULL;
    }
    temp->data = data;
    temp->next = NULL;
    if (*head == NULL) {
        *head = temp;
        return 1;
    }
    Node* p_prev = *head;
    while (p_prev->next) {
        p_prev = p_prev->next;
    }
    p_prev->next = temp;
    return 1;
}

/**
 * @brief 链表遍历
 * @param[in] head 链表
*/
void node_print(Node* head)
{
    Node* temp = head;
    printf("List is:");
    while (temp) {
        printf(" %d", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

/**
 * @brief 链表反向
 * @param[in] head 链表
*/
void node_reverse(Node** head)
{
    Node* p_prev = NULL;
    Node* p_curr = *head;
    Node* p_next = NULL;
    while (p_curr) {
        p_next = p_curr->next;
        p_curr->next = p_prev;
        p_prev = p_curr;
        p_curr = p_next;
    }
    *head = p_prev;
    return ;
}

然后在main()函数中进行测试

#include <stdio.h>
#include "node.h"

int main()
{
    Node *head = NULL;
    node_add(&head, 1);
    node_add(&head, 2);
    node_add(&head, 3);
    node_add(&head, 4);
    node_print(head);
    node_reverse(&head);
    node_print(head);
    return 0;
}

运行结果:

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值