9/10 每日一題(鏈結串列 回傳中間以後的鏈結)
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
n=0
p=head
while p:
n+=1
p=p.next
p=head
mid=n//2
n=0
while p:
if n == mid:
head=p
#來到中間點,回傳剩下的鏈結串列
return head
n+=1
p=p.next
--------------------------------使用雙指針
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
while(fast and fast.next): #避免fast在None,沒有next屬性
fast = fast.next.next
slow = slow.next
return slow-----------------------------------------------
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp=head
c=0
while(temp!=None):
c=c+1
temp=temp.next
if(c%2!=0):
pos=c//2
temp=head
i=1
while(i<=pos):
temp=temp.next
i=i+1
return temp
else:
pos=c//2
temp=head
i=1
while(i<=pos):
temp=temp.next
i=i+1
return temp標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁