1
我已經實現了一個鏈接列表類,並且我創建了一個可在常規列表上工作的selectionSort和insertionSort函數。我需要讓selectionSort和insertionSort工作在鏈表上,但我不確定從哪裏開始,如果我是誠實的。如何在Python的鏈表上實現SelectionSort和InsertionSort?
這裏是我的鏈表類:
class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self,newdata):
self.data = newdata
def setNext(self, newnext):
self.next = newnext
class unorderedList:
def __init__(self):
self.head = None
def isEmpty(self):
return self.head == None
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
def length(self):
current = self.head
count = 0
while current != None:
count = count + 1
current = current.getNext()
return count
def search(self, item):
current = self.head
found = False
while current != None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self, item):
current = self.head
previous = None
found = False
while not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
self.head = current.getNext()
else:
previous.setNext(current.getNext()
這是我的選擇排序和插入排序的代碼。他們在常規列表上工作得很好,但我很難找出從哪裏開始讓他們在鏈表上工作(無序列表)。
def selectionSort(alist):
for fillslot in range(len(alist)-1,0,-1):
positionOfMax = 0
for location in range(1,fillslot+1):
if alist[location]>alist[positionOfMax]:
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position] = alist[position-1]
position = position-1
alist[position] = currentvalue
任何建議/提示將不勝感激。
真棒。我運行了你的代碼,它完美運行。 我會盡力讓選擇排序 - 這應該是非常有幫助的! – user4208546 2014-11-03 00:40:56
因此,對於選擇排序...我只會遍歷每個節點的數據,並且如果當前節點的數據大於先前的節點,那麼該節點將被設置爲一個變量,例如最大的變量。它將作爲這個變量保持下去,直到下一個節點中的一個變大,然後最大變化。 然後一旦到達列表的末尾,最大值將與最後一個項目交換位置(一旦我到了列表的末尾,它應該是當前節點)。 試圖在我嘗試編碼之前試着去思考它! @Taha – user4208546 2014-11-03 01:16:42