BM1反转链表[栈+头插法]

题目要求如下:
问题比较简单,就是将链表中的值进行反转即可。

一种比较简单的方式是使用栈+链表的方式来实现,下面是相应的代码:

复制代码
#include <stdio.h>
#include <stdlib.h>
int arr[10001] = {0};
struct ListNode* ReverseList(struct ListNode* head ) {
    if (head == NULL) {
        return head;
    }
    int num = 0;
    struct ListNode* node;
    //遍历列表并入栈
    while ((head->next) != NULL) {
        arr[num] = head->val;
        head = head->next;
        num++;
    }
    node = head;
    arr[num] = head->val;
    struct ListNode* p;
    //使用头插法将链表的值反转
    for (int i = 0; i < num; i++) {
        p = (struct ListNode*)malloc(sizeof(struct ListNode));
        p->val = arr[i];
        p->next = node->next;
        node->next = p;
    }
    return node;
}

对于入栈,可以定义1个整数型的数组遍历链表将其值添加到数组中。再利用头插法一次将栈中的值添加到链表中并返回即可实现链表的反转效果。

下面是最终的效果:

相关推荐
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr3 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_33 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.3 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.3 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣3 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9923 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王3 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水3 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1013 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质