Leetcode 02.06. 回文链表

 

  利用递归的回路进行比对。

  C:

#include "stdbool.h"
#include <string.h>

struct ListNode
{
    int val;
    struct ListNode *next;
};

struct ListNode *rightNode;

bool isPal(struct ListNode *node)
{
    if (node != NULL)
    {
        if (!isPal(node->next))
            return false;
        if (node->val != rightNode->val)
            return false;
        rightNode = rightNode->next;
    }
    return true;
}

bool isPalindrome(struct ListNode *head)
{
    rightNode = head;
    return isPal(head);
}

  JAVA:

    private ListNode rightNode;

    public final boolean isPalindrome(ListNode head) {
        rightNode = head;
        return isPal(head);
    }

    private final boolean isPal(ListNode node) {
        if (node != null) {
            if (!isPal(node.next)) return false;
            if (node.val != rightNode.val) return false;
            rightNode = rightNode.next;
        }
        return true;
    }

  JS:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
var rightNode;

/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function (head) {
    rightNode = head;
    return isPal(head);
};

var isPal = function (node) {
    if (node != null) {
        if (!isPal(node.next)) return false;
        if (node.val != rightNode.val) return false;
        rightNode = rightNode.next;
    }
    return true;
}

 

posted @ 2022-03-09 14:04  牛有肉  阅读(17)  评论(0编辑  收藏  举报