判斷單鏈表迴文的三種方法

Everyone thinks of changing the world, but no one thinks of changing himself. 
每一個人都想要改變世界,卻沒人想過要改變本身。

上海自來水來自海上,中山諸羅茶羅諸山中。很是有意境的句子,正着讀倒着讀都是一個意思。很是對陳,強迫症患者福音。本文分享了基於單鏈表判斷迴文的三種方法。全部源碼均已上傳至github:連接java

基於數組

用數組存儲鏈表前半段的值,使用快慢指針法來進行截取。

可是這種數組的倒序插入比較費時。node

小技巧:一直使用node.add(0,slow.data)至關於倒序插入git

private boolean isPalindromeByArray(Node node) {
        if (null == node || null == node.next) return true;
        List<Integer> nodeList = new ArrayList<>();
        Node fast = node;
        Node slow = node;
        nodeList.add(0, slow.data);
        while (null != fast.next && null != fast.next.next) {
            fast = fast.next.next;
            slow = slow.next;
            nodeList.add(0, slow.data);
        }
        Node curNode = slow;
        if (null != fast.next) {
            curNode = slow.next;
        }
        int index = 0;
        while (null != curNode) {
            if (curNode.data != nodeList.get(index)) {
                return false;
            }
            curNode = curNode.next;
            ++index;
        }
        return true;
    }複製代碼

基於棧

和數組的思想是同樣的,只不過存儲方式換成了棧,而後不斷地出棧和鏈表後半段比較便可。這種方式比較高效。

private boolean isPalindromeByStack(Node node) {
        if (null == node || null == node.next) return true;
        Stack<Integer> stack = new Stack<>();
        Node fast = node;
        Node slow = node;
        stack.push(slow.data);
        while (null != fast.next && null != fast.next.next) {
            fast = fast.next.next;
            slow = slow.next;
            stack.push(slow.data);
        }
        if (null != fast.next) {
            slow = slow.next;
        }
        Node curNode = slow;
        while (null != curNode) {
            if (curNode.data != stack.pop()) {
                return false;
            }
            curNode = curNode.next;
        }
        return true;
    }複製代碼

原地鏈表法

不借助外部存儲來實現判斷迴文,這裏用到了鏈表反轉的思想。先使用快慢指針法找到鏈表的後半部分,而後將其反轉再進行比較

private boolean isPalindromeAuto(Node node) {
        if (null == node || null == node.next) return true;
        Node fast = node;
        Node slow = node;
        while (null != fast.next && null != fast.next.next) {
            fast = fast.next.next;
            slow = slow.next;
        }
        Node preNode = slow;
        Node firstNode = slow.next;
        Node curNode = slow.next.next;
        firstNode.next = null;
        while (null != curNode) {
            Node nextNode = curNode.next;
            curNode.next = preNode.next;
            preNode.next = curNode;
            curNode = nextNode;
        }
        slow = node;
        fast = preNode.next;
        while (null != fast) {
            if (fast.data != slow.data) {
                return false;
            }
            slow = slow.next;
            fast = fast.next;
        }
        return true;
    }複製代碼

測試結果


end


您的點贊和關注是對我最大的支持,謝謝!
相關文章
相關標籤/搜索