单向链表反转

比如有一个链表是这样的,1->2->3->4->5,反转后成为 5->4->3->2->1

public class MyLinkedList {

    Node head;
    // 1->2->3->4->5

    // 最新添加的节点为head
    public void add(int obj) {
        Node newNode = new Node(obj);
        if (head == null) {
            head = newNode;
        } else {
            newNode.next = head;
            head = newNode;
        }
    }

    // 遍历时候,要新建一个引用first保存head。直接使用head会在遍历完后head的值被修改为null
    public void display() {
        Node first = head;
        StringBuilder sb = new StringBuilder();
        while (first != null) {
            sb.append(first.value + " -> ");
            first = first.next;
        }
        String res = sb.substring(0, sb.lastIndexOf(" -> "));
        System.out.println(res);
    }

    public static class Node {

        Node next;
        int value;

        public Node(int value) {
            super();
            this.value = value;
        }
    }

    //
    public void reverse() {
        // 如果头节点或者第二个节点是null,直接返回
        if (head == null || head.next == null) {
            return;
        }
        // 头节点设置为pre,第二个节点设置为当前节点,头节点的下一个设置为null,因为反转以后,头节点就成为最后一个节点了
        Node pre = head;
        Node cur = head.next;
        pre.next = null;
        while (cur != null) {
            // 将当前节点的下一个临时保存
            Node next = cur.next;
            // 当前节点的下一个指向pre
            cur.next = pre;
            // 进行下一轮的循环,当前节点变为下一个节点的next,当前节点右移
            pre = cur;
            cur = next;
        }
        // 重新调整head的指向
        head = pre;
    }

    // 这种写法和上面的都是相同的流程,只不过更加简洁
    public void reverse2() {
        Node pre = null;// 当前结点的前结点
        Node next = null;// 当前结点的后结点
        while (head != null) {// 从左到右,依次把->变为<-
            next = head.next;
            head.next = pre;// 当前结点指向前面的结点
            pre = head;// pre结点右移
            head = next;// head结点右移
        }
        this.head = pre;
    }

    public static void main(String[] args) {

        MyLinkedList linkedList = new MyLinkedList();
        linkedList.add(5);
        linkedList.add(4);
        linkedList.add(3);
        linkedList.add(2);
        linkedList.add(1);
        linkedList.display();
        linkedList.reverse2();
        linkedList.display();
    }

}
原文地址:https://www.cnblogs.com/moris5013/p/11629738.html