单向链表反转

记录几种单项链表反转的实现,代码仅java实现。
链表结点结构定义为:

    public class Node {
        int val;
        Node next;

        public Node() {}
        public Node(int val) {
            this.val = val;
        }
    }

单向链表创建

终端输入字符串以 # 结束
输入示例:2 3 4 5 #

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Node head = null;
        Node parent = null;
        while(sc.hasNext()) {
            String ipt = sc.next();
            if (ipt.equals("#")) break;
            int val = Integer.valueOf(ipt);
            if (parent == null) {
                head = new Node(val);
                parent = head;
                continue;
            }
            Node node = new Node(val);
            parent.next = node;
            parent = node;
        }
        sc.close();
    }

递归

    /**
     * @param head
     * @return
     */
    private static Node reverseQueue(Node head) {
        if(head == null) return null;
        if (head.next == null) 
            return head;
        Node newHead = reverseQueue(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

非递归

使用栈(额外空间复杂度高)

    /**
     * @param head
     * @return
     */
    private static Node reverseQueue(Node head) {
        Stack<Node> nodes = new Stack<>();
        while (head != null) {
            nodes.push(head);
            head = head.next;
        }
        Node pre = null;
        Node newHead = null;
        while(!nodes.isEmpty()) {
            if (pre == null) {
                newHead = nodes.pop();
                pre = newHead;
                continue;
            }
            pre.next = nodes.peek();
            pre = nodes.pop();
        }
        // important !!!
        pre.next = null;
        return newHead;
    }

额外空间复杂度O(1)

    /**
     *  非递归,额外空间O(1)
     * @param head
     * @return
     */
    private static Node reverseQueue3(Node head) {
        if (head == null) return null;
        Node cur = head.next;
        Node tmp = null;
        // 第一个结点的后继结点要设为null
        if (cur != null) {
            tmp = cur;
            cur = cur.next;
            tmp.next = head;
            head.next = null;
        }
        while(cur != null) { 
            head = tmp;
            tmp = cur;
            cur = cur.next;
            tmp.next = head;
        }
        return tmp;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值