题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
直接思路
偏向于把链表当作数组来理解题目,站在数组的角度,想到双指针法,两个指针分别从前后两个方向出发,走数组长度的一半路程,出现不一样的情况表示非回文链表,反之正确。
这里要注意的问题是首先确定数组长度也就是链表结构的长度,但链表结构与数组结构本质不同:
- 数组列表底层是通过对应位置的存储值,即利用数组下标值就可以在常数时间内得到列表内任何位置的值;
- 链表存储的是结点对象,每个结点存储值和下一个结点的指针,在查找某个特定索引的结点时通过指针来完成,需要O(n)的时间。
于是想到把链表的值赋值到数组列表中,再使用双指针法。
- 时间复杂度 O(n)
- 空间复杂度 O(n) ,遍历所有链表结点,数组空间随节点数变化
学习借鉴
优化思路
即反转链表,为了不遍历所有链表,对链表原地反转,最后需要进行恢复,从完整思路来考虑,破坏原链表结构,存在弊端。
提交代码
直接思路
# 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:
array = []
cur_node = head
while cur_node is not None:
array.append(cur_node.val)
cur_node = cur_node.next
first = 0
last = len(array) - 1
while first < last:
if array[first] == array[last]:
last -= 1
first += 1
else:return False
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:
if head is None:
return True
# 找到前半部分链表的尾节点并反转后半部分链表
first_half_end = self.end_of_first_half(head)
second_half_start = self.reverse_list(first_half_end.next)
# 判断是否回文
result = True
first_position = head
second_position = second_half_start
while result and second_position is not None:
if first_position.val != second_position.val:
result = False
first_position = first_position.next
second_position = second_position.next
# 还原链表并返回结果
first_half_end.next = self.reverse_list(second_half_start)
return result
def end_of_first_half(self, head):
fast = head
slow = head
while fast.next is not None and fast.next.next is not None:
fast = fast.next.next
slow = slow.next
return slow
def reverse_list(self, head):
previous = None
current = head
while current is not None:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previous
学习总结
- 链表结构是一种逻辑结构,只有遍历所有结点才知道存储数目
- 操作链表结构的函数调用