栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

单链表反转

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单链表反转

思路
  • 都是一个思路,在遍历的过程中改变指针。
心路历程

递归卡住了,我想的是利用return来完成指针的修改,但这样拿不到整个反转链表的头
最后看的别人的,return专门用来传递反转链表的头
first.next = null;如果忽略,最后两个节点会不断循环

两指针

    public static  Node reverse1(Node first) {
        if(first == null)
            return null;
        Node prev = null;
        Node next = first;
        for (Node node = first; node != null; node = next) {
            next = node.next;
            node.next = prev;
            prev = node;
        }
        return prev;
    }
//    反转链表 递归
    public static  Node reverse2(Node first)  {
        if(first == null||first.next == null)
            return first;
        else  {
//            head代表整个队列的头,first是每次递归的头
            Node head = reverse2(first.next);
            first.next.next = first;
            first.next = null;
            return head;
        }
    }

递归

//    反转链表 递归
    public static  Node reverse2(Node first)  {
        if(first == null||first.next == null)
            return first;
        else  {
//            head代表整个队列的头,first是每次递归的头
            Node head = reverse2(first.next);
            first.next.next = first;
            first.next = null;
            return head;
        }
    }

递归优化

//    反转链表 递归优化
    public static  Node reverse3(Node first) {
        if(first == null)
            return null;
        Stack> stack = new Stack<>();
        for (Node node = first;node!=null;node = node.next){
            stack.push(node);
        }
        first = stack.pop();
        Node prev;
        while(!stack.isEmpty()){
            prev = stack.pop();
            prev.next.next = prev;
            System.out.println("item"+prev.item);
            prev.next = null;
        }
        return first;
    }

Node类

public class Node {
    Node next;
    Node prev;

    T item;

    public Node() {
    }

    public Node(T item,Node next) {
        this.next = next;
        this.item = item;
    }

    public Node(Node prev,T item,Node next) {

        this.prev = prev;
        this.item = item;
        this.next = next;
    }
// 最后返回的是item的toString
    @Override
    public String toString() {
        return item.toString();
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/993469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号