1:兩數相加
給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每個節點只存儲單個數字。將兩數相加返回一個新的鏈表。
你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
分析:對應節點一一相加;注意進位
思路:%10計算當前位數字,//10計算進位值,flag進位標誌位,創建一個啞節點作爲返回的頭節點
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution(object):
def addTwoNumbers(self,l1,l2):
"""
:type l1:ListNode
:type l2:ListNode
:rtype:ListNode
"""
if l1 is None:
return l2
if l2 is None:
return l1
tmp=ListNode(0) #創建一個啞節點
res=tmp #遊標res
flag=0 #加法運算的進位標誌位
while l1 or l2:
tmpsum=0
if l1:
tmpsum=l1.val
l1=l1.next
if l2:
tmpsum+=l2.val
l2=l2.next
tmpres=(tmpsum+flag)%10 #
flag=(tmpsum+flag)//10 #更新加法運算的進位標誌位
res.next=ListNode(tmpres) #計算值賦予一個新的節點
res=res.next #節點更新
if flag: #這個是一種特殊情況 當出現最高位進位,
res.next=ListNode(1)
res=tmp.next #鏈表表頭
del tmp #釋放節點tmp
return res
2:鏈表的部分反轉:
給定一個鏈表,翻轉該鏈表從m到n的位置。要求直接翻轉而非申請新空間。 如:給定1->2->3->4->5,m=2,n=4,返回1->4->3->2->5。假定給出的參數滿足:1≤m≤n≤鏈表長度。
#時間複雜度O(n),空間複雜度O(1)
class ListNode(object):
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def ReverseList(head,m,n):
if not head:
return None
#定義兩個遊標指針
pre=None
cur=head
while m>1: #cur移動到要交換的節點,pre爲cur前一個節點
pre=cur
cur=cur.next
m-=1 #m移動到1
n-=1 #n移動到m-n+1
#定義兩個新的遊標指針,用於反轉後鏈表與原鏈表的連接:
tail=cur #初始化爲鏈表的頭部,爲反轉後鏈表的尾指針
con=pre #爲反轉後鏈表的頭指針
#鏈表反轉
while n:
t=cur.next # 這裏用t來暫存cur.next節點
cur.next=pre #反轉
pre=cur #前移pre
cur=t
#將反轉鏈表與原鏈表相連接
if con:
con.next=pre
else:#如果只有一個頭節點
head=pre
tail.next=cur
return head
3:鏈表劃分:
給定一個鏈表和一個值x,將鏈表劃分成兩部分,使得劃分後小於x的結點在前,大於等於x的結點在後。在這兩部分中要保持原
鏈表中的出現順序。如:給定鏈表1->4->3->2->5->2和x = 3,返回1->2->2->4->3->5
分析:遍歷鏈表,小於x的放在一起
這樣需要兩個鏈表:一個存放小於x的節點;另一個存放相反狀態。之後將兩個鏈表連接在一起。
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def partition(self,head,x):
#創建兩個鏈表
before_head=ListNode(0) #啞ListNode(0),before_head作用和head一樣
before=before_head #遊標指針
after_head=ListNode(0) #啞ListNode(0),after_head作用和head一樣
after=after_head #遊標指針
while head: #用head遍歷鏈表,head爲第一個節點
if head.val<x: #小於x的存放在一個鏈表中
before.next=head
before=before.next
else:#反之存放在另一個鏈表中
after.next=head
after=after.next
head=head.next
#兩個鏈表拼接
after.next=None
before.next=after_head.next
return before_head.next
4:刪除排序鏈表中的重複元素
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self,head):
if head==None or head.next==None:
return head
h=head #遊標節點 因爲要和h.next.next這個比較所以這裏不再是head!=None,而是
while h!=None:
if h.val=h.next.val:
h.next=h.next.next #刪除操作
#這裏遊標不後移
else:
h=h.next #遊標後移(指針後移)
return head
5:環形鏈表:
思路:判斷一個鏈表是否爲環形鏈表,見了快慢指針,當兩者相遇時即爲環形鏈表:
slow=slow.next
fast=fast.next.next
class ListNode:
def __init__(self,x):
self.val=x
self.next=None
class Solution:
def hasCycle(self, head):
if not head or not head.next:
return False
slow=head#慢指針
fast=head.next#快指針
while slow!=fast: #循環結束標誌 快慢指針相遇
if fast==None:
return False
else:
slow=slow.next #慢指針
fast=fast.next.next#快指針
return True