请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
最常规最简单的做法,直接把值存到list,list与反转list相同的话就是回文链表。
# 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:
res = []
while(head):
res.append(head.val)
head = head.next
return res == res[::-1]
递归:
# 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.first = head #实例对象变量,在loop里可以调用
def loop(cur):
if cur:
#走到None的时候,if cur false,直接跳到return True,回到None的上一个节点也就是最后一个节点。
#只要有一个节点比较失败,则返回前一个cur时,loop(cur.next)为False,return False
if not loop(cur.next):
return False
if self.first.val != cur.val:
return False
self.first = self.first.next
return True
return loop(head)
之前想的把列表砍成两半比较
# 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:
res = []
while(head):
res.append(head.val)
head = head.next
med = len(res)//2
if res[:med]==res[med:][::-1] and len(res)%2==0:
return True
elif res[:med+1]==res[med:][::-1] and len(res)%2==1:
return True
else:
return False
快慢指针:这个砍成两半的想法就与快慢指针类似
# 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:
if not head or not head.next:
return True
slow= fast = head #快慢指针指向头
res = [] #用一个栈来装慢指针的值
while(fast and fast.next):
res.append(slow.val)
slow = slow.next
fast = fast.next.next
# 这里慢指针返回中位数节点
if fast: #链表的长度是奇数
slow = slow.next
while(slow and res):
val = res.pop()
if val!=slow.val:
return False
slow = slow.next
return True
直接用栈也可,利用栈的先进后出特性
# 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:
res = [] #stack res
cur = head
while(cur):
res.append(cur.val)
cur = cur.next
while(head):
val = res.pop()
if head.val != val:
return False
head = head.next
return True