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

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

    结束!

  • 相关阅读:
    域运算符::
    类和结构体类型的异同
    4 链表组件(817)
    2 旋转链表(61)
    1、重排链表(力扣143)
    子字符串排序的关键代码
    C语言四舍五入
    约分
    python学习第八天
    python学习第七天
  • 原文地址:https://www.cnblogs.com/aaronthon/p/13614681.html
Copyright © 2011-2022 走看看