lintcode-入门5题python语言

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 18:54   1601   0

466. 链表节点计数

"""
Definition of ListNode
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""

class Solution:
    """
    @param head: the first node of linked list.
    @return: An integer
    """
    def countNodes(self, head):
        # write your code here
        count = 1
        if head == None:
            return 0
        while head.next != None:
            head = head.next
            count += 1
        return count

484. 交换数组两个元素

class Solution:
    """
    @param A: An integer array
    @param index1: the first index
    @param index2: the second index
    @return: nothing
    """
    def swapIntegers(self, A, index1, index2):
        # write your code here
        temp = A[index1]
        A[index1] = A[index2]
        A[index2] = temp

632. 二叉树的最大节点

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param: root: the root of tree
    @return: the max node
    """
    def maxNode(self, root):
        # write your code here
        if root == None:
            return None
        max = root
        if root.left != None:
            leftMax = self.maxNode(root.left)
            if leftMax.val > max.val:
                max = leftMax
        if root.right != None:
            rightMax = self.maxNode(root.right)
            if rightMax.val > max.val:
                max = rightMax
        return max
        

763. Hex Conversion

class Solution:
"""
@param n: a decimal number
@param k: a Integer represent base-k
@return: a base-k number
"""
def hexConversion(self, n, k):
# write your code here
if n == 0:
return "0"

ret_num = ''

while n > 0:
t = n % k
c = ''
if t <= 9: #0 ~ 48
c = ord('0') + t
else: #A ~ 65
c = ord('A') + (t - 10)
print(c)

ret_num = chr(c) + ret_num
n = int(n / k)

452. 删除链表中的元素

参考(下次能独立写出):https://blog.csdn.net/guoziqing506/article/details/51273818



分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP