Acwing 35. 反转链表

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

思考题:

请同时实现迭代版本和递归版本。

数据范围

链表长度 [0,30]

样例

复制代码
输入:1->2->3->4->5->NULL
输出:5->4->3->2->1->NULL

思路

很怪,这个头结点不是指的不存储任何信息的结点,更类似于头指针
代码

javascript 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null, cur = head;
        //必须这么写,如果写成pre = head, cur = head -> next会陷入死循环
        while(cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

递归代码

javascript 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode tail = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return tail;
    }
}
相关推荐
lingchen19061 天前
b = [1 2 3;4 5 6;7 8 9]>> b(2,2)=[ ]??? Subscripted assignme
数据结构·算法
Vect__1 天前
二叉树实战笔记:结构、遍历、接口与 OJ 实战
数据结构·c++·算法
haoly19891 天前
数据结构与算法篇--结构不变式--动态数组
数据结构·不变式
爱和冰阔落1 天前
【C++ STL栈和队列下】deque(双端队列) 优先级队列的模拟实现与仿函数的介绍
开发语言·数据结构·c++·算法·广度优先
『往事』&白驹过隙;1 天前
ARM环境日志系统的简单设计思路
linux·c语言·数据结构·物联网·iot·日志系统
光电笑映1 天前
C++list全解析
c语言·开发语言·数据结构·c++·list
952361 天前
数据结构—双链表
c语言·开发语言·数据结构·学习
haoly19892 天前
数据结构与算法篇--语义智能指针设计模式
数据结构·设计模式
努力写代码的熊大2 天前
list的使用
数据结构·list