mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2024-12-27 12:56:17 +00:00
添加cpp,py和js (上半部分)
This commit is contained in:
parent
ef1da6bf6f
commit
b48730dd5b
@ -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<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
|
||||
```
|
||||
|
||||
这个方法可以直接通过,但是这个方法需要辅助数组,那我们还有其他更好的方法吗?
|
||||
|
||||
双指针翻转链表法
|
||||
|
Loading…
Reference in New Issue
Block a user