Java 实现链表反转

static class Node {
        int val;
        Node next;

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

    /**
     * 翻转链表
     * @param head
     * @return
     */
    private static Node reverse(Node head) {
        //如果head为null,直接返回null
        if (head == null) {
            return null;
        }
        //如果head没有next节点,无需反转,直接返回head
        if (head.next == null) {
            return head;
        }
        //定义三个变量用于临时存储
        Node pre = head, cur = head.next, next = null;
        //head此时是链表的尾部,所以没有next节点
        pre.next = null;
        while (cur.next != null) {
            //记录next节点
            next = cur.next;
            //原来的前节点变为自己的next
            cur.next=pre;
            //当前的节点变为记录为自己next的前一节点
            pre = cur;
            //当前节点更改为本次当前节点的next
            cur = next;
        }
        //此时当前节点是原链表的尾节点,将其next改为其原来的前节点即可
        cur.next = pre;
        return cur;
    }

    /**
     * 输出链表
     * @param head
     */
    private static void printNodeList(Node head) {
        if (head == null) {
            return;
        }
        Node _node = head;
        while (_node != null) {
            System.out.print(_node.val);
            _node = _node.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node node = new Node(1);
        Node node2 = new Node(2);
        node.next = node2;
        Node node3 = new Node(3);
        node2.next = node3;
        Node node4 = new Node(4);
        node3.next = node4;
        printNodeList(node);
        Node newHead = reverse(node);
        printNodeList(newHead);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值