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; }
当你看清人们的真相,于是你知道了,你可以忍受孤独