项目做多了,最近对数据结构以及算法突然感兴趣。 做个题目玩玩:
题目如题,要求用一遍遍历实现。
一开始看到题目, 想到了反序然后求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