算法设计题(要求同上):给定单链表,请设计时空效率尽可能高的算法,判断它是否中心对称。例如abcdcba即中心对称。注:表头指针为head,结点结构为(data, next)。
时间: 2024-02-18 22:01:19 浏览: 16
好的,这是一道经典的链表题目,以下是我的算法设计:
1. 首先找到链表的中心点,可以使用快慢指针来实现。同时记录下中心点的位置。
2. 从中心点开始,将后面的链表翻转。
3. 从链表的头部和中心点往后遍历,判断每个节点的值是否相同,如果都相同则说明该链表是中心对称的。
4. 将后面翻转的链表再进行一次翻转,恢复原来的链表。
5. 返回结果。
以下是代码实现:
```python
def is_symmetric(head):
if not head or not head.next:
return True
# 找到链表的中心点,同时记录下中心点的位置
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 翻转链表的后半部分
prev, cur = None, slow
while cur:
next_node = cur.next
cur.next = prev
prev = cur
cur = next_node
# 判断链表是否中心对称
left, right = head, prev
while right:
if left.data != right.data:
return False
left = left.next
right = right.next
# 恢复原来的链表
prev, cur = None, prev
while cur:
next_node = cur.next
cur.next = prev
prev = cur
cur = next_node
slow.next = prev
return True
```
以上就是我的算法设计,时间复杂度为 O(n),空间复杂度为 O(1)。