Leetcode - 链表专题 - 876

给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

示例 1:

输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.

示例 2:

输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。

提示:

  • 给定链表的结点数介于 1 和 100 之间。

方法一:使用列表进行转换

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        data = []
        while head:
            data.append(head.val)
            head = head.next
        length = len(data) 
        temp = data[length/2:]
        ptr = ListNode(0)
        ptr1 = ptr
        for item in temp:
            ptr.next = ListNode(item)
            ptr = ptr.next
        return ptr1.next

方法二: 设定一个记数变量进行计数

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        count = 0
        ptr = head
        while ptr:
            ptr = ptr.next
            count += 1
        if count == 1:
            return head
        count = count / 2
        for i in range(0, count-1):
            head = head.next
        return head.next

猜你喜欢

转载自blog.csdn.net/jhlovetll/article/details/84574805
今日推荐