当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3实现的判断回文链表算法示例

Python3实现的判断回文链表算法示例

2019年03月19日  | 移动技术网IT编程  | 我要评论

年年发棋牌评测,福晋悠闲,hookport.sys

本文实例讲述了python3实现的判断回文链表算法。分享给大家供大家参考,具体如下:

问题:

请判断一个链表是否为回文链表。

方案一:指针法

class solution:
  def ispalindrome(self, head):
    """
    判断一个链表是否是回文的,很自然的想法就是两个指针,一个指针从前往后走,一个指针从后往前走,判断元素值是否相同,这里要分几个步骤来进行求解:
1、找到链表长度的一半,用追赶法,一个指针一次走两步,一个指针一次走一步
2、将后一半数组转置
3、判断链表是否是回文链表
    :type head: listnode
    :rtype: bool
    """
    slow = fast = head
    while fast and fast.next:
      slow = slow.next
      fast = fast.next.next
     node = none
    while slow:
      nxt = slow.next
      slow.next = node
      node = slow
      slow = nxt
     while node and head:
      if node.val != head.val:
        return false
      node = node.next
      head = head.next
    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):
    """
    :type head: listnode
    :rtype: bool
    """
    res = []
    cur = head
    while cur:
      res.append(cur.val)
      cur = cur.next
    return res == res[: : -1]

更多关于python相关内容感兴趣的读者可查看本站专题:《python数据结构与算法教程》、《python加密解密算法与技巧总结》、《python编码操作技巧总结》、《python函数使用技巧总结》、《python字符串操作技巧汇总》及《python入门与进阶经典教程

希望本文所述对大家python程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网