文章最前: 我是Octopus,这个名字来源于我的中文名--章鱼;我热爱编程、热爱算法、热爱开源。所有源码在我的个人github ;这博客是记录我学习的点点滴滴,如果您对 Python、Java、AI、算法有兴趣,可以关注我的动态,一起学习,共同进步。
相关文章:
- LeetCode:55. Jump Game(跳远比赛)
- Leetcode:300. Longest Increasing Subsequence(最大增长序列)
- LeetCode:560. Subarray Sum Equals K(找出数组中连续子串和等于k)
文章目录:
题目描述:
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
java实现方法1:
/**
* 判断链表是不是回文链表
*
* @param head 头结点
* @return 布尔值
*/
public boolean isPalindrome(ListNode head) {
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
return isPalindromeList(list);
}
/**
* 判断list是不是连续节点
*
* @param list 链表
* @return 布尔值
*/
public boolean isPalindromeList(List<Integer> list) {
int i = 0;
int j = list.size() - 1;
while (i < j) {
if (list.get(i).equals(list.get(j))) {
return false;
}
i++;
j--;
}
return true;
}
时间复杂度:O(n)
空间复杂度:O(n)
python实现方法1:
def is_palindrome_list(self, node_list: ListNode) -> bool:
'''
判断链表是否是回文串
Args:
node_list: node链表
Returns:
布尔值
'''
i, j = 0, len(node_list) - 1
while i < j:
if node_list[i] != node_list[j]:
return False
i += 1
j -= 1
return True
def is_palindrome(self, head: ListNode) -> bool:
'''
返回交点
Args:
head: 节点head
Returns:
布尔值
'''
node_list = []
if not head:
return True
while head:
node_list.append(head.val)
head = head.next
return self.is_palindrome_list(node_list)
时间复杂度:O(n)
空间复杂度:O(n)