• 单项链表的实现以及容器化(类封装实现)


    实例化一个新的linkedlist ,开始 head和tail都是空,append第一个值的时候,分别赋值给head  和 tail 也就是第一个值,分别属于头和尾,

    在添加,tail就往后移动。最终tail表示最后一个元素,并且,tail的next是None。

    链表的特点:

      手拉手,前一个数据知道下一个数据的内存地址,

      获取某个值,只能遍历,从头到尾,遍历

      增删比较容易,知道地址,就可以直接找到。

      pop也很容易(最后一个),只需处理tail就行。  

     1 # 单项链表:
     2 class Node:
     3     def __init__(self, node=None, next=None):
     4         self.node = node
     5         self.next = next
     6 
     7     def __repr__(self):
     8         return '{} --> {}'.format(self.node, None if self.next is None else self.next.node)
     9 
    10 class SingalLinkList:
    11     def __init__(self, head= None, tail=None):
    12         self.head = head
    13         self.tail = tail
    14         self.len = 0
    15 
    16     def append(self, node):
    17         node = Node(node)
    18         if self.head is None:
    19             self.head = node
    20         else:
    21             self.tail.next = node
    22         self.tail = node
    23         self.len += 1
    24 
    25     def __iter__(self):
    26         if self.head is None:
    27             raise  Exception('This is a Emppty linklist')
    28         current = self.head
    29         while current:
    30             yield current
    31             current = current.next
    32 
    33     def __getitem__(self, index):
    34         if index < 0:
    35             raise IndexError('not supports negative index')
    36         if self.head is None:
    37             raise Exception('Empty')
    38 
    39         current = None
    40         for i, v in enumerate(ll):
    41             if i == index:
    42                 current = v
    43                 break
    44         else:
    45             raise IndexError('index out of range')
    46         return current
    47 
    48     def __setitem__(self, index, value):
    49         ll[index].node = value
    50 
    51     def __len__(self):
    52         return self.len
    53 
    54     def remove(self):#需要把前一个也记录下来。
    55         pass
    56     def pop(self):# 一样,也需要把前一个记录下来,直接找self.tail 就行
    57         pass
    58 
    59 
    60 
    61 ll = SingalLinkList()
    62 ll.append(1)
    63 ll.append(2)
    64 ll.append(3)
    65 for i in ll:
    66     print(i)
    67 ll[2] = 33
    68 for i in ll:
    69     print(i)
    70 print(ll[2])
    71 print(len(ll))
    为什么要坚持,想一想当初!
  • 相关阅读:
    程序员优化程序流程
    iOS开发优化的25个方案
    彻底解决_OBJC_CLASS_$_某文件名", referenced from:问题转
    svn服务器搭建与配置
    mac 显示隐藏文件夹
    HDU 2276 Kiki & Little Kiki 2 矩阵构造
    HDU 3306 Another kind of Fibonacci ---构造矩阵***
    HDU 1575 Tr A----矩阵相乘题。
    矩阵的模板----
    HDU 1757 矩阵求第n的递推式
  • 原文地址:https://www.cnblogs.com/JerryZao/p/9700290.html
Copyright © 2020-2023  润新知