文巾解题 876. 链表的中间结点
生活随笔
收集整理的這篇文章主要介紹了
文巾解题 876. 链表的中间结点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 題目描述
2 解題思路
2.1 輔助數組?
用一個輔助數組,記錄鏈表里面的值,然后取數組中間的值
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object):def middleNode(self, head):lst=[head]while(head.next!=None):lst.append(head.next)head=head.nextreturn(lst[len(lst)//2])2.2 計算鏈表長度
先計算鏈表長度,再取一半長的那個值。
注意,偶數的話是取后面那個中間的數,所以這里需要(N+1)//2
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object):def middleNode(self, head):n=0tmp=headwhile(head.next!=None):n+=1head=head.nextprint(n)for i in range((n+1)//2):tmp=tmp.nextreturn(tmp)2.3 快慢指針
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object):def middleNode(self, head):fast=headslow=headwhile(fast!=None and fast.next!=None):fast=fast.next.nextslow=slow.nextreturn slow總結
以上是生活随笔為你收集整理的文巾解题 876. 链表的中间结点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NTU -SCSE-orientatio
- 下一篇: 文巾解题 19. 删除链表的倒数第 N