Leetcode——Middle of the Linked List (不定期更新链表提醒及解题思路大杂烩)

题目:返回列表中间数,如果链表长度为奇数,中间数即为中间位置的数值。如果链表长度为偶数,则返回是链表中间两位偏向于右边的数值[1]。
知道Python中链表表示没啥的,直接上代码吧,后期不定期更新链表相关题目。

class Solution:
    def middleNode(self, head):
        nodes = []

        while head is not None:
            nodes.append(head)
            head = head.next

            # node = nodes[len(nodes)//2]
        # return node
        return nodes[len(nodes)//2]

一个完整案例代码如下:

#
#
# Definition for singly-linked list.
from pandas import json


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def middleNode(self, head):
        nodes = []

        while head is not None:
            nodes.append(head)
            head = head.next

            # node = nodes[len(nodes)//2]
        # return node
        return nodes[len(nodes)//2]

def stringToIntegerList(input):
    return json.loads(input)

def stringToListNode(input):
    # Generate list from the input
    numbers = stringToIntegerList(input)

    # Now convert that list into linked list
    dummyRoot = ListNode(0)
    ptr = dummyRoot
    for number in numbers:
        ptr.next = ListNode(number)
        ptr = ptr.next

    ptr = dummyRoot.next
    return ptr

def listNodeToString(node):
    if not node:
        return "[]"

    result = ""
    while node:
        result += str(node.val) + ", "
        node = node.next
    return "[" + result[:-2] + "]"

def main():
    import sys
    def readlines():
        for line in sys.stdin:
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            head = stringToListNode(line);

            ret = Solution().middleNode(head)

            out = listNodeToString(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

后续有时间更新链表定义、常见题型及解题方法
————20180909————–我是分割线—————-

Ref:
https://leetcode.com/problems/middle-of-the-linked-list/

猜你喜欢

转载自blog.csdn.net/woai8339/article/details/82555315