java实现链表反转的三种方式

7 篇文章 0 订阅

分别通过栈、递归、指针的方式实现:

import java.util.Stack;

public class ReverseLinkedList {

    public static void main(String[] args) {
        ReverseLinkedList reverseLinkedList = new ReverseLinkedList();
        reverseLinkedList.test();
    }

    public void test() {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        node1.setNext(node2);
        node2.setNext(node3);
        //方法需要替换
        node1 = reverseByPointer(node1);
        while (node1 != null) {
            System.out.println(node1.val);
            node1 = node1.getNext();
        }
    }

    //栈实现
    private Node reverseByStack(Node head) {
        if (head == null || head.getNext() == null) {
            return head;
        }
        Stack<Node> stack = new Stack<>();
        while (head != null) {
            stack.push(head);
            head = head.getNext();
        }
        head = stack.pop();
        Node tmp = head;
        while (!stack.empty()) {
            Node node = stack.pop();
            node.setNext(null);
            tmp.setNext(node);
            tmp = node;
        }
        return head;
    }

    //递归实现
    private Node reverseByRecursion(Node head) {
        if (head == null || head.getNext() == null) {
            return head;
        }
        //递归获取当前节点的后一个节点
        Node tmp = reverseByRecursion(head.getNext());
        Node node = head.getNext();
        head.setNext(null);
        node.setNext(head);
        return tmp;
    }

    //指针实现
    private Node reverseByPointer(Node head) {
        if (head == null || head.getNext() == null) {
            return head;
        }
        //pre指针指向前一个节点,初始第一个节点的前节点为空
        Node pre = null;
        //tmp指针指向当前节点
        Node tmp = null;
        while (head != null) {
            //tmp指针指向head头指针节点
            tmp = head;
            //head头指针向后遍历
            head = head.getNext();
            //反转,设置当前节点的下一个节点为前一个节点
            tmp.setNext(pre);
            //pre指针向后移动,指向当前节点
            pre = tmp;
        }
        return tmp;
    }

    private class Node {
        private int val;

        private Node next;

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

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值