单链表反转 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);
        }
    }
}


目录
相关文章
|
9月前
|
消息中间件 Kubernetes NoSQL
LeetCode 1359、1360
LeetCode 1359、1360
|
算法 C++ Python
每日算法系列【LeetCode 881】救生艇
每日算法系列【LeetCode 881】救生艇
|
算法 C++
每日算法系列【LeetCode 827】最大人工岛
每日算法系列【LeetCode 827】最大人工岛
130 0
leetcode 827 最大人工岛
leetcode 827 最大人工岛
66 0
leetcode 827 最大人工岛
LeetCode 389. 找不同
给定两个字符串 s 和 t,它们只包含小写字母。
87 0
leetcode 283 移动零
leetcode 283 移动零
64 0
leetcode第34题
从左向右遍历,一旦出现等于 target 的值就结束,保存当前下标。如果从左到右没有找到 target,那么就直接返回 [ -1 , -1 ] 就可以了,因为从左到右没找到,那么从右到左也一定不会找到的。如果找到了,然后再从右到左遍历,一旦出现等于 target 的值就结束,保存当前下标。 时间复杂度是 O(n)并不满足题意,但可以了解下这个思路,从左到右,从右到左之前也遇到过。
leetcode第34题
|
存储 算法
leetcode第49题
时间复杂度:两层 for 循环,再加上比较字符串,如果字符串最长为 K,总的时间复杂度就是 O(n²K)。 空间复杂度:O(NK),用来存储结果。 解法一算是比较通用的解法,不管字符串里边是大写字母,小写字母,数字,都可以用这个算法解决。这道题的话,题目告诉我们字符串中只有小写字母,针对这个限制,我们可以再用一些针对性强的算法。 下边的算法本质是,我们只要把一类的字符串用某一种方法唯一的映射到同一个位置就可以。
196 0
leetcode第49题