項目做多了,最近對數據結構以及算法突然感興趣。 做個題目玩玩:
題目如題,要求用一遍遍歷實現。
一開始看到題目, 想到了反序然後求k個,但是這樣的話就需要n+k次,不是一邊遍歷了。 後來一下,可以設置兩個同步的指針, 之間間隔是k個,然後同步走,當前面的到達終點後,第二部是不就是倒數第k個了嗎?
Python 代碼:
'''
Created on Feb 26, 2013
'''
if __name__ == '__main__':
pass
head = {}
#construct the dict
for item in range(0, 100):
#construct the list
dict1 = {'value':item,'next':[]}
if not head:
tmp = dict1
head = dict1
else:
tmp['next'] = dict1
tmp = dict1
#print the list
#tmp = head
#while tmp:
# print tmp['value']
# tmp = tmp['next']
#find the least K
#find the first K elems
i = 0
k = 1
tmp = head
while i <= k and tmp:
tmp = tmp['next']
i+=1
finder = head
while tmp:
tmp = tmp['next']
finder = finder['next']
print finder