問題背景:面臨秋招,需要刷《劍指offer》了 /慘
參考鏈接:
https://www.cnblogs.com/kumata/p/9147077.html
https://www.cnblogs.com/yupeng/p/3413763.html
一、鏈表簡介
鏈表是通過一個個節點(Node)組成的,每個節點都包含了稱爲數據域(value)和指針域(next)的基本單元。示意圖如下:
數據域/值域:用來存放用戶數據;
指針域:用來存放指向下一個元素的指針。
head: 指向第一個節點
tail: 指向最後一個節點
None: 鏈表中最後一個節點的指針域爲None值
注:這些節點在邏輯上是相連的,但在物理內存上並不相連。
一、定義
定義節點類
class Node(object):
def __init__(self,val,p=0):
self.data = val #數據域
self.next = p #指針域
有了節點之後,定義鏈表類
class LinkList(object):
def __init__(self):
self.head = 0
def initlist(self,data):
self.head = Node(data[0]) #head節點
p = self.head
for i in data[1:]:
node = Node(i) #存入數據域
p.next = node #指針域
p = p.next
對這個類進行實例化
l = LinkList()
l.initlist([1,2,3,4,5]) #創建了一個鏈表
二、解題
以下都是我自己的解法,可能不是最優解,只是通過了測試~
1)輸入一個鏈表,輸出該鏈表中倒數第k個結點。
class Solution:
def FindKthToTail(self, head, k):
# write code here
arr=[] #定義一個數組
while head!=None: #當還沒到遍歷完
arr.append(head)
head=head.next
if k>len(arr) or k<1:
return #return 與return None相同,會結束函數
return arr[-k]
2)輸入一個鏈表,反轉鏈表後,輸出新鏈表的表頭。
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
if pHead==None: #空鏈表
return None
if pHead.next==None: #只有一個節點
return pHead
last=None
while pHead!=None:
tmp=pHead.next #暫存下一節點
pHead.next = last #當前節點指向上一節點
last = pHead #前進一格,上一節點變爲當前節點
pHead = tmp #前進一格,當前節點變爲下一節點
return last
3)輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,當然我們需要合成後的鏈表滿足單調不減規則。
class Solution:
# 返回合併後列表
def Merge(self, pHead1, pHead2):
# write code here
result=ListNode(0) #定義一個含有100個節點的鏈表,存儲結果
p=result
while pHead1 and pHead2: #只要遍歷完其中一個鏈表就可以
if pHead1.val<=pHead2.val:
result.next=pHead1
pHead1=pHead1.next
elif pHead1.val>pHead2.val:
result.next=pHead2
pHead2=pHead2.next
result=result.next
if pHead1!=None: #看誰還剩下
result.next=pHead1
elif pHead2!=None:
result.next=pHead2
return p.next #這裏如果寫return p會把頭節點也包含進去