本文为作者学习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-1和i中间
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)
请在转载文章过程中明确标注文章出处!尊重原创,尊重知识产权,谢谢!