234. 回文链表
- 题:回文链表
- 解:
1. 使用栈
先遍历链表将数据压入栈中,然后再次遍历链表与出栈的数据做对比,如果有不相同的说明不是回文链表。
时间开销O(n) 空间开销O(n)
-
Python3
# 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 stack = [] ptr1 = head while ptr1: stack.append(ptr1.val) ptr1 = ptr1.next ptr2 = head print(stack) while len(stack): tmp = stack.pop() print(tmp) if tmp != ptr2.val: return False ptr2 = ptr2.next return True
使用数组加双指针
遍历链表将数据存到数组中,转为简单的回文串问题去解决。
时间开销O(n) 空间开销O(n)
反转链表
- 使用快慢指针找到链表的中间节点
- 从中间节点开始将后面的链表反转
- 从链表的两端开始向中间遍历,对比数据,如果有不一样的则说明不是回文链表。
时间开销O(n) 空间开销O(1)
-
Python3
# 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 # 快慢指针找中心 fast = head slow = head while fast: slow = slow.next fast = fast.next.next if fast.next else fast.next # 反转后半段的链表 pre = None next = None while slow: next = slow.next slow.next = pre pre = slow slow = next ptr = head while pre: if pre.val != ptr.val: return False ptr = ptr.next pre = pre.next return True
-
Go
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func isPalindrome(head *ListNode) bool { slow := head fast := head for fast!=nil { slow = slow.Next if fast.Next != nil { fast = fast.Next.Next }else{ fast = fast.Next } } var pre *ListNode var next *ListNode for slow != nil { next = slow.Next slow.Next = pre pre = slow slow = next } ptr := head for pre != nil { if pre.Val != ptr.Val { return false } pre = pre.Next ptr = ptr.Next } return true }