【每天进步一点点】反转链表(双指针法)

79 阅读1分钟

反转链表(双指针法)

实现方式有很多,优先考虑双指针法,易实现、容易理解 !!!

反转链表是一些算法题的基本操作,比如回文链表中也有用到反转链表的知识

这一个个小技能恰恰是解题的关键

图示

reserveList.gif

代码( java实现 )

public class ReverseListDemo {
    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        printLinkList(head);
        printLinkList(reverseList(head));
    }

    // cur 转向,pre 移动,cur 移动,next 移动
    public static Node reverseList(Node cur) {
        if (cur == null || cur.next == null) {
            return cur;
        }
        Node pre = null;
        Node next = cur.next; // 提前保存下一个节点
        while (cur != null) {
            cur.next = pre;
            pre = cur;
            cur = next;
            next = next == null ? null : next.next;
            //=== 循环结束,cur、next 均为 null ===
        }
        return pre;
    }

    public static void printLinkList(Node head) {
        System.out.print("LinkList : ");
        while (head != null) {
            System.out.print(head.data);
            if (head.next != null) {
                System.out.print(" -> ");
            }
            head = head.next;
        }
        System.out.println();
    }

    public static class Node {
        private int data;
        private Node next;
        public Node(int data) {
            this.data = data;
        }
    }
}

运行结果

reserveList1.png