添加cpp,py和js (上半部分)

This commit is contained in:
jaredliw 2021-07-12 20:25:03 +08:00
parent ef1da6bf6f
commit b48730dd5b

View File

@ -35,6 +35,8 @@
**题目代码** **题目代码**
Java Code:
```java ```java
class Solution { class Solution {
public boolean isPalindrome(ListNode head) { public boolean isPalindrome(ListNode head) {
@ -64,6 +66,83 @@ class Solution {
``` ```
C++ Code:
```cpp
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> 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
```
这个方法可以直接通过但是这个方法需要辅助数组那我们还有其他更好的方法吗 这个方法可以直接通过但是这个方法需要辅助数组那我们还有其他更好的方法吗
双指针翻转链表法 双指针翻转链表法