有一个带头结点的循环双链表L,其结点的data成员值为整数,设计一个算法判断其所有元素是否为对称。如果从前向后读和从后向前都得到的数据序列相同,表示为对称;否则不是对称。
1条回答 默认 最新
- 游一游走一走 2022-10-26 20:53关注
class ListNode: def __init__(self, data, next = None, pre=None): self.data = data self.next = next self.pre = pre def make_list(elements): head = ListNode(elements[0]) tail = head for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next cuurentNode=ListNode(element) ptr.next = cuurentNode cuurentNode.pre=ptr tail = cuurentNode tail.next=head head.pre=tail return head class Solution(object): def isPalindrome(self, head): node1=head node2=head.pre while node1!=node2 and node1.next!=node2: if node1.data!=node2.data: return False else: node1=node1.next node2=node2.pre return True ob1 = Solution() print(ob1.isPalindrome(make_list([1]))) print(ob1.isPalindrome(make_list([1,2,3,3,1]))) print(ob1.isPalindrome(make_list([1,2,3,2,1]))) print(ob1.isPalindrome(make_list([1,2,3,3,2,1])))
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
- ¥15 Python3.5 相关代码写作
- ¥20 测距传感器数据手册i2c
- ¥15 RPA正常跑,cmd输入cookies跑不出来
- ¥15 求帮我调试一下freefem代码
- ¥15 matlab代码解决,怎么运行
- ¥15 R语言Rstudio突然无法启动
- ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
- ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
- ¥15 用windows做服务的同志有吗