面试-链表逆置 作业手写一个单链表,并且实现单链表元素的逆置,(a0, a1,a2,a3,..an)-> (an,an-1,… a1, a0),算法的空间复杂度和时间复杂度经可能低

题目:手写一个单链表,并且实现单链表元素的逆置,(a0, a1,a2,a3,..an)-> (an,an-1,… a1, a0),算法的空间复杂度和时间复杂度经可能低?


代码如何下:

package com;

public class LinkedList<T> {

    public Node<T> head = null;//链表第一个元素

    public void add(T newItem) {
        Node newNode = new Node(newItem);
        if (null == head) {//添加第一个元素
            head = newNode;
        } else {//添加后面的元素
            Node<T> tail = head;
            while (tail.next != null) {
                tail = tail.next;//指针循环找到链表的最后一个元素
            }
            tail.next = newNode;//最后一个元素指向提那家的元素
        }
    }


    /**
     * 打印链表
     */
    public void display() {
        Node<T> node = head;
        int i = 0;
        while (node != null) {
            System.out.print(String.format("(%d=%d)->", i++, node.item));
            node = node.next;
        }
        System.out.println();
    }

    /**
     * 循环的方式逆置
     * 思路:不断提那家元素为第一个节点,原来元素一次后退
     */
    public void reverse() {
        Node curr = head;
        Node reve = null;//逆置后当前元素的下一个元素指针变量,逆置前为第一个节点
        while (curr != null) {
            Node temp = curr;
            curr = curr.next;
            temp.next = reve;//表示当前元素指向该元素的后面
            reve = temp;//
        }
        head = reve;
    }


    int i = 0;

    /**
     * 递归的方式逆置
     * 思路:如,1,2,3,4   该方法执行顺序2->1,3->2,4->3
     */
    public Node<T> reverse(Node<T> head) {
        if (head == null || head.next == null) {
            return head;//保证head为倒数第二个元素
        }
        Node<T> tail = reverse(head.next);//循环找到链表的最后一个元素,辅助为tail
        System.out.println(head.item + " : " + tail.item);
        head.next.next = head;
        System.out.println(head.item + " : " + head.next.item + "指向" + head.next.next.item);
        head.next = null;
        System.out.println(head.item + " : " + head.item + "指向null");
        i++;
        System.out.println("------------------");
        return tail;
    }


    /**
     * 定义类
     *
     * @author sj  E-mail: 961784535@qq.com
     * @version 创建时间: 2017-11-12 下午11:10:55
     *          类说明:
     */
    class Node<T> {
        public T item;
        public Node<T> next;


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


}


main方法运行


代码1结果如下:


代码2结果如下:















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值