链表数据结构(Python)

本文为作者学习python数据结构链表学习笔记
欢迎交流讨论,喜欢的话点个赞吧

欢迎去看我的主页: NicholasYe’s Homepage.


1. 初始化单向链表与定义单个节点

class Node(object):

    # define a default Node 
    def __init__(self, data, next = None):
        self.data = data
        self.next = next

# Three ways to create a new node
Node1 = None                # 1. Empty Link
Node2 = Node("A", None)     # 2. A node with data but not link
Node3 = Node("B", Node2)    # 3. A node with data and links to node2

2. is_empty() 链表是否为空

    def is_empty(self):
        """判断链表是否为空"""
        return self.head is None

3. length() 链表长度

    def length(self):
        """链表长度"""
        # 初始指针指向head
        probe = self.head
        count = 0
        # 指针指向None 表示到达尾部
        while probe is not None:
            count += 1
            # 指针下移
            probe = probe.next
        return count

4. 在任意位置插入节点

  • 注意事项(在位置i处插入节点):
    • 在对应位置插入节点是需要判断节点位置i是否超出节点长度n
    • 如果没有超出长度n,则意味着0<i<n,应该把新元素放在i-1i中间
if head is None or index <= 0:
    head = Node(newItem, head)
else:
    # Search for node at position i-1 or the last position
    probe = head
    while index > 1 and probe.next != None:
        probe = probe.next
        index -= 1
    # Insert new node after probe at position
    probe.next = Node(newItem, probe.next)

5. 在任意位置删除节点

  • 注意事项(在位置i处删除节点):
    • 有可能链表无节点或者只有一个节点
    • 有可能超出链表长度n或者正好是最后一个节点
    • 如果没有超出长度n,则意味着0<i<n,应该删除i-1后面的节点
if index <= 0 or head.next is None:
    removedItem = head.data
    head = head.next
    return removedItem
else:
    # Search for node at position i-1 or the last
    probe = head
    while index > 1 and probe.next.next != None:
        probe = probe.next
        index -= 1
    # delete the node and return the new LinkedList
    removedItem = probe.next.data
    probe.next = probe.next.next
    return removedItem

6. 双向链接结构

class TwoWayNode(object):

    # define a two way Node 
    def __init__(self, data, previous = None, next = None):
        Node.__init__(self, data, next)
        self.previous = previous

7. 单向链表成环

    head = Node (None, None)
    head.next = head

    # Search for node at position i-1 or last position
    probe = head
    while index > 0 and probe.next != head:
        probe = probe.next
        index -= 1
    # Insert new node after node at position i-1 or last position
    probe.next = Node(newItem, probe.next)

请在转载文章过程中明确标注文章出处!尊重原创,尊重知识产权,谢谢!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值