单链表的链表反转

/**
 * 单链表的链表反转
 * node1 -> node2 -> node3
 * node3 -> node2 -> node1
 */
public class LinkInversion {

    public static void main(String[] args) {
        Node node1 = new Node("node1");
        Node node2 = new Node("node2");
        Node node3 = new Node("node3");
        node1.setNext(node2);
        node2.setNext(node3);
        Node inversion = inversion2(node1);
        System.out.println("反转后的数据:" + inversion.getData());
        while (inversion != null) {
            System.out.println(inversion.getData() + ":" + inversion.getNext());
            inversion = inversion.getNext();
        }
    }


    /**
     * 不推荐
     *
     * @param firstNode
     * @return
     */
    private static Node inversion(Node firstNode) {
        if (firstNode == null) {
            return null;
        }
        Node next = firstNode.getNext();
        Node currentNode = firstNode;
        Node pre = null;
        while (next != null) {
            currentNode.next = pre;
            Node nodeNext = next.next;
            next.setNext(currentNode);
            pre = currentNode;
            currentNode = next;
            next = nodeNext;
        }
        return currentNode;
    }


    /**
     * 推荐
     *
     * @param firstNode
     * @return
     */
    private static Node inversion2(Node firstNode) {
        if (firstNode == null) {
            return null;
        }
        if (firstNode.next == null) {
            return null;
        }
        Node preNode = null;
        Node currNode = firstNode;
        Node nextNode = null;
        while (currNode != null) {
            nextNode = currNode.next;
            currNode.setNext(preNode);
            preNode = currNode;
            currNode = nextNode;
        }
        return preNode;
    }


    static class Node {
        private String data;
        private Node next;

        public Node(String data) {
            this.data = data;
        }

        public String getData() {
            return data;
        }

        public void setData(String data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

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

发布了62 篇原创文章 · 获赞 0 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_40720919/article/details/100063647