Python基礎程式設計練習LeetCode 鍊錶

2021-09-18 05:17:52 字數 2997 閱讀 5857

python基礎程式設計練習leetcode——鍊錶

給出乙個鍊錶: 1->2->3->4->5 和 n = 2.

鍊錶:1->2->3->5.

解題思路:本題需要兩個指標,pre和end。一開始初始化時使得pre指標指向煉表頭節點head,end指標指向pre+n的節點位置。同時往後移動pre和end指標位置,使得end指標指向最後乙個節點,那麼pre指標指向的則是end-n的節點位置(即倒數第n個元素的前乙個節點),則將其刪除。

class

solution

: def removenthfromend

(self, head: listnode, n: int)

-> listnode:

pre = head

end = head

for i in

range

(n):

end = end.next

if end is none:

return head.next

while end.next is not none:

pre = pre.next

end = end.next

pre.next = pre.next.next

return head

1->2->4, 1->3->4

1->1->2->3->4->4

解題思路:新建乙個空鍊錶,只要兩個鍊錶不為空,比較兩個鍊錶中當前值,小的放入l空煉表中,並把指標後移,直到某一煉表為空,並把非空的鍊錶全部接到l空煉表上。

class

solution

: def mergetwolists

(self, l1: listnode, l2: listnode)

-> listnode:l=

while(1

):if l1==none or l2==none:

break

if(l1.val <= l2.val):l

.(l1.val)

l1=l1.next

else:l

.(l2.val)

l2=l2.next

if l1==none:

while

(l2!=none):l

.(l2.val)

l2=l2.next

elif l2==none:

while

(l1 != none):l

.(l1.val)

l1 = l1.next

return

l

head = [3,2,0,-4], pos = 1

true

解題思路:用快慢指標來解決這個問題。乙個指標每次走兩步,乙個每次走一步,如果有環,那麼兩個指標就會有重合。

class

solution

(object)

: def hascycle

(self, head)

:"""

:type head: listnode

:rtype: bool

"""if head == none or head.next == none:

return false

p1=p2=head

while p2.next and p2.next.next != none:

p1=p1.next

p2=p2.next.next

if p1==p2: #存在環就會出現相等

return true

return false

1->2->3->4->5->null

5->4->3->2->1->null

class

solution

(object)

: def reverselist

(self, head)

:"""

:type head: listnode

:rtype: listnode

"""cur = head

pre = none

while cur:

nex = cur.next # 節點原地反轉

cur.next = pre

pre = cur

cur = nex # 進入下乙個要反轉的節點

return pre

1->2->2->1

true

解題思路:利用快慢指標找到鍊錶的中點,將鍊錶的後半部分反序後和鍊錶的前半部分進行對比。

class

solution

: def ispalindrome

(self, head: listnode)

-> bool:

if head==none or head.next==none:

return true

fast=slow=q=head

while fast and fast.next:

slow=slow.next

fast=fast.next.next

p=self.

reverselist

(slow) #p為後半部分鍊錶反序後的head

while p:

if p.val != q.val:

return false

p=p.next

q=q.next

return true

def reverselist

(self,head)

: pre=none

cur=head

tmp=none

while cur:

tmp=cur.next

cur.next=pre

pre=cur

cur=tmp

return pre

Python基礎程式設計練習(二)

python基礎程式設計練習 二 輸入a,b的值,用空格隔開 計算結果 n,m map int,input split def getvalue n if n 0 or n 1 return 1else return n getvalue n 1 def value n,m first getval...

Python程式設計 基礎練習 一

from datetime import datetime 求多少以內的素數 n 100000 count 0start datetime.now for i in range 2 n 1 for j in range 2 i if i j 0 是合數 break else 是素數 count 1 ...

Python程式設計基礎之小案例練習

re庫 re庫是python的標準庫,主要用於字串匹配。方法解釋說明 re.search 在乙個字串中搜尋匹配正規表示式的第乙個位置,返回match物件 re.match 從乙個字串的開始位置起匹配正規表示式,返回match物件 re.findall 搜尋字串,以列表型別返回全部能匹配的字串 re....