1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第二百三十四题
(1)题目
英文:
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
中文:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
(2)解法
① 先将复杂的链表转换为list,然后再用左右逼近的方式判断回文
(耗时:92ms,内存:23.8M)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
num = []
node = head
while(node):
num.append(node.val)
node = node.next
length = len(num)
for i in range(length//2):
if num[i]!=num[length-1-i]:
return False
return True
② 使用堆栈
(耗时:80ms,内存:23.8M)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
stack = []
curr = head
while(curr):
stack.append(curr)
curr = curr.next
node1 = head
while(stack):
node2 = stack.pop()
if node1.val != node2.val:
return False
node1 = node1.next
return True
③ 递归法
(耗时:100ms,内存:76M)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
self.front_pointer = head
def recursively_check(current_node=head):
if current_node is not None:
if not recursively_check(current_node.next):
return False
if self.front_pointer.val != current_node.val:
return False
self.front_pointer = self.front_pointer.next
return True
return recursively_check()