diff --git a/animation-simulation/链表篇/234. 回文链表.md b/animation-simulation/链表篇/234. 回文链表.md index fe3e1ed..4619206 100644 --- a/animation-simulation/链表篇/234. 回文链表.md +++ b/animation-simulation/链表篇/234. 回文链表.md @@ -35,6 +35,8 @@ **题目代码** +Java Code: + ```java class Solution { public boolean isPalindrome(ListNode head) { @@ -46,7 +48,7 @@ class Solution { arr.add(copynode.val); copynode = copynode.next; } - // 双指针遍历数组 + //双指针遍历数组 int back = 0; int pro = arr.size() - 1; while (back < pro) { @@ -64,6 +66,83 @@ class Solution { ``` +C++ Code: + +```cpp +class Solution { +public: + bool isPalindrome(ListNode* head) { + vector arr; + ListNode* copynode = head; + while (copynode) { + arr.push_back(copynode->val); + copynode = copynode->next; + } + int back = 0; + int pro = arr.size() - 1; + while (back < pro) { + if (arr[back] != arr[pro]) { + return false; + } + back++; + pro--; + } + return true; + } +}; +``` + +JS Code: + +```js +var isPalindrome = function(head) { + let arr = []; + let copynode = head; + //将链表的值复制到数组中 + while (copynode) { + arr.push(copynode.val) + copynode = copynode.next + } + //双指针遍历数组 + let back = 0; + let pro = arr.length - 1; + while (back < pro) { + //判断两个指针的值是否相等 + if (arr[back] !== arr[pro]) { + return false + } + //移动指针 + back += 1 + pro -= 1 + } + return true +}; +``` + +Python Code: + +```py +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + arr = [] + copynode = head + # 将链表的值复制到数组中 + while copynode is not None: + arr.append(copynode.val) + copynode = copynode.next + # 双指针遍历数组 + back = 0 + pro = len(arr) - 1 + while back < pro: + # 判断两个指针的值是否相等 + if arr[back] != arr[pro]: + return False + # 移动指针 + back += 1 + pro -= 1 + return True +``` + 这个方法可以直接通过,但是这个方法需要辅助数组,那我们还有其他更好的方法吗? 双指针翻转链表法