要求将算法7-13设计为3. 4. 1节定义的带头结点
要求将算法7-13设计为3. 4. 1节定义的带头结点单链表LinkedList类的方法。
8.设计算法,判断单链表中的元素是否中心对称。例如,线性表(1, 2, 3, 2, 1)及(1.2. 2. 1)是中心对称的。
答案
class LNode: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = LNode(None) # 头结点 def reverse(self, p): """反转以p为首的子链表,返回新头结点""" pre = None cur = p while cur: nxt = cur.next cur.next = pre pre = cur cur = nxt return pre def is_symmetry(self): """判断单链表是否中心对称""" if self.head.next is None: return True # 快慢指针找中点 slow = self.head.next fast = self.head.next while fast.next and fast.next.next: slow = slow.next fast = fast.next.next # 反转后半部分 half_head = self.reverse(slow.next) p1 = self.head.next p2 = half_head ok = True while p2 is not None: if p1.data != p2.data: ok = False break p1 = p1.next p2 = p2.next # 恢复链表(可选,保持原链表不变) slow.next = self.reverse(half_head) return ok