算法题 — 链表反转

将单链表的链接顺序反转过来

  • 例:输入:1->2->3->4->5
  • 输出:5->4->3->2->1

使用两种方式解题

链表

1 迭代

遍历

static class ListNode {
   
    int val;
    ListNode next;

    public ListNode(int val, ListNode next) {
   
        this.val = val;
        this.next = next;
    }
}

public static ListNode reverseList(ListNode head) {
   
    if (head == null || head.next == null) {
   
        return head;
    }
    ListNode pre = null, cur = head, next;
    while (cur != null) {
   
        // 保存下一个节点
        next = cur.next;
        // 反转链表
        cur.next = pre;
        pre = cur;
        cur = next;
    }
    return pre;
}

public static void main(String[] args) {
   
   ListNode node5 = new ListNode(5, null);
   ListNode node4 = new ListNode(4, node5);
   ListNode node3 = new ListNode(3, node4);
   ListNode node2 = new ListNode(2, node3);
   ListNode node1 = new ListNode(1, node2);
   reverseList(node1)
}

2 递归

迭代

public static ListNode recursion(ListNode head) {
   
    if (head == null || head.next == null) {
   
        return head;
    }

    ListNode newHead = recursion(head.next);
    head.next.next = head;
    head.next = null;

    return newHead;
}

相关推荐

  1. 算法】92. II

    2024-01-27 10:44:02       27 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-27 10:44:02       14 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-27 10:44:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-27 10:44:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-27 10:44:02       18 阅读

热门阅读

  1. mysql双机bin-log备份

    2024-01-27 10:44:02       38 阅读
  2. Eureka Server和Eureka Client

    2024-01-27 10:44:02       32 阅读
  3. 多表查询,

    2024-01-27 10:44:02       27 阅读
  4. 嵌入式——从入门到精通第十一天

    2024-01-27 10:44:02       32 阅读
  5. linux部署es8.0版本以及启动了浏览器访问不了

    2024-01-27 10:44:02       30 阅读
  6. C# 中的接口

    2024-01-27 10:44:02       31 阅读
  7. 目标检测中目标的尺寸差异大会存在什么问题?

    2024-01-27 10:44:02       37 阅读
  8. Compose中添加Android原生控件

    2024-01-27 10:44:02       41 阅读
  9. vue3中页面传参汇总

    2024-01-27 10:44:02       40 阅读
  10. sql注入之into outfile语句写入一句话木马

    2024-01-27 10:44:02       40 阅读