python實現單鏈表,基本Python語法
阿新 • • 發佈:2018-12-16
Python使用起來真的非常舒服,完全的貼合程式編寫者的思維方式,語言也很平易近人。昨天看了點基礎入門的書籍,發現確實使用很方便。寫個單鏈表,聯絡一下最最最最基本的語法。
#print用法 #print ("Welcome to python!") #name = input('input your name:') #print (name.capitalize()) #print ('hello ' + name.capitalize() + '!') ''' #Python for迴圈 冒泡 def bubbleSort(nums): for i in range(len(nums)-1): for j in range(len(nums)-1-i): if(nums[j] > nums[j+1]): nums[j], nums[j+1] = nums[j+1], nums[j] return nums nums = [1,4,7,2,9,3,6,4] nums=bubbleSort(nums) print (nums) #列印整個陣列 for i in range (len(nums)): print (nums[i], end=" ") #自定義列印,end=" ",將換行符換成" " #while迴圈 ar = [1,2,3,4,5,6,7,8,9] i=0 while i < len(ar): print(ar[i], end=" ") i = i+1 #連結串列 class Node: def __init__(self, idata): self.data = idata self.next = 0; class List: def __init__(self): self.head = 0; self.next = 0 def getlength(self): length=0 p=self.head while p.next != 0 : length = length+1 p = p.next return length def inserttail(self, idata): node = Node(idata) p=self.data while p.next != 0 : p = p.next p.next = node def inserthead(self, idata): node = Node(idata) node.next = self.next self.next = node def show(self): p = self.next while p != 0 : print(p.data, end=" ") p = p.next print(" ") def deleteone(self, idata): left = self; right = self.next; while right != 0 : if right.data == idata : left.next = right.next break else : left = left.next right = right.next def deleteall(self, idata): left = self; right = self.next; while right != 0 : if right.data == idata : left.next = right.next else : left = left.next right = right.next def findnumcount(self, idata) : #find num of allcount p = self.next count = 0 while p != 0: if idata == p.data : count = count+1 p = p.next return count def reverse(self): left = 0; mid = self.next; if mid == 0 : return NONE right = mid.next; while right != 0 : mid.next = left left = mid mid = right right = right.next mid.next = left self.next = mid list = List() ar = [3,1,2,3,4,3,5,6,3,7,3] for i in range (len(ar)): list.inserthead(ar[i]) print("find allcount of num: 3 ", list.findnumcount(3)) list.show() list.deleteone(3) list.show() list.deleteall(3) list.show() print("find allcount of num: 3 ", list.findnumcount(3)) list.reverse() list.show() #氣泡排序 ar = [3,6,1,5,7,9,2,5] for i in range(len(ar)): for j in range(len(ar)-1-i): if ar[j] > ar[j+1] : ar[j], ar[j+1] = ar[j+1], ar[j] print(ar) #斐波那契 num = int(input("input count: ")) if num <= 0 : print("argument error!") elif num == 1 or (num == 2) : print("end: ", 1) else : numone, numtwo, count = 1, 1, 2 while count < num : count += 1 numtmp = numtwo numtwo = numone + numtwo numone = numtmp print("end: ", numtwo) '''