zoukankan      html  css  js  c++  java
  • 单链表操作之替换

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

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

    结束!

  • 相关阅读:
    Hibernate 中出现 XXXX is not mapped 问题
    记录一下表格用poi的导出word
    [转帖] 悟透JavaScript
    JAVA读取Oracle中的blob图片字段并显示
    vs2010代码段,用得飞起~
    FontFamily获取中文名字
    vs2010快捷键
    WPF Binding基础
    Binding对数据的转换和校验
    WPF个UI元素
  • 原文地址:https://www.cnblogs.com/aaronthon/p/13614681.html
Copyright © 2011-2022 走看看