单链表反转 LeetCode 206

简介: 单链表反转 LeetCode 206

单链表反转 2种方法

  1. 空间换时间
  2. 时间换空间
package com.stan.work;
public class Step1 {
    /**
     * 单链表反转     206
     * 链表中环的检测  141
     * 两个有序的链表合并
     * 删除链表倒数第 n 个结点
     * 求链表的中间结点
     */
    /**
     * 自定义链表
     */
    public static class MyLinkNode {
        int val;
        MyLinkNode next;
        MyLinkNode() {
        }
        MyLinkNode(int val) {
            this.val = val;
        }
        MyLinkNode(int val, MyLinkNode next) {
            this.val = val;
            this.next = next;
        }
    }
    public static void main(String[] args) {
        MyLinkNode head = new MyLinkNode(1);
        MyLinkNode node1 = new MyLinkNode(2);
        MyLinkNode node2 = new MyLinkNode(3);
        MyLinkNode node3 = new MyLinkNode(4);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        MyLinkNode node = reverseList(head);
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println();
    }
    /**
     * 迭代翻转
     *
     * @param head
     * @return
     */
    public static MyLinkNode reverseList(MyLinkNode head) {
        MyLinkNode curr = head;
        MyLinkNode prev = null;
        while (curr != null) {
            // 先换指针位置 再换next值
            MyLinkNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
    /**
     * 递归翻转
     *
     * @param head
     * @return
     */
    public static MyLinkNode reverseList1(MyLinkNode head) {
        //递归出口
        if (head == null || head.next == null) {
            return head;
        }
        //先递后归
        MyLinkNode p = reverseList1(head.next);
        head.next.next = head;
        head.next = null;
        return p;
    }
    public static void searchNode(MyLinkNode head) {
        if (head == null) {
            return;
        }
        while (head != null && head.next != null) {
            System.out.print(head.val);
        }
    }
}


目录
相关文章
|
21天前
LeetCode
LeetCode
22 0
|
21天前
leetcode-1219:黄金矿工
leetcode-1219:黄金矿工
45 0
|
21天前
|
消息中间件 Kubernetes NoSQL
LeetCode 1359、1360
LeetCode 1359、1360
leetcode 283 移动零
leetcode 283 移动零
38 0
|
C++ Python
LeetCode 771. Jewels and Stones
LeetCode 771. Jewels and Stones
62 0
|
机器学习/深度学习
LeetCode:605. 种花问题
LeetCode:605. 种花问题
93 0
leetcode
在排序数组中查找元素的第一个和最后一个位置
|
算法
leetcode第47题
基本上都是在上道题的基础上改出来了,一些技巧也是经常遇到,比如先排序,然后判断和前一个是否重复。利用 Hash 去重的功能。利用原来的存储空间隐藏掉数据,然后再想办法还原。
leetcode第47题
leetcode第44题
时间复杂度:text 长度是 T,pattern 长度是 P,那么就是 O(TP)。 空间复杂度:O(TP)。 同样的,和第10题一样,可以优化空间复杂度。
leetcode第44题
leetcode第55题
当自己按照 45 题的思路写完的时候,看 Solution 的时候都懵逼了,这道题竟然这么复杂?不过 Solution 把问题抽象成动态规划的思想,以及优化的过程还是非常值得学习的。
leetcode第55题

热门文章

最新文章