在单链表结构中的替换也利用了遍历模式。这种情况下,我们在链表结构中搜索一个给定项或一个给定位置,并且用新的项替换该项。第一个操作,即替换一个给定的项,并不需要假定目标项在链表结构中。如果目标项不存在,那就不会发生替换,并且该操作返回False。如果目标项存在,新的项会替换它,并且该操作返回True。代码如下:

# coding: utf-8
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next


head = None

for count in range(1,6):
head = Node(count, head)
print head.data, head.next,head

targetItem = 2
newItem = 100
probe = head
while probe != None and targetItem != probe.data:
probe = probe.next
if probe != None:
probe.data = newItem
print True
else:
print False

还有一个替换第i项的操作,形式如下:

 

# coding: utf-8
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next


head = None

for count in range(1,6):
head = Node(count, head)
print head.data, head.next,head

probe = head
index = 3
newItem = 100
while index >0:
probe = probe.next
index -= 1
probe.data = newItem

两种替换操作在平均情况下都是线性的。

结束!