'''
定义python中的单向不循环的链表
non-circular, singly linked list
链表是数据结构与算法中的知识,表示将多个节点连接起来的结构
每个节点由两个部分组成:数据域和指针域
数据域表明当前节点的数值,指针域表明当前节点的后继节点的地址
顺序表中的数值在内存中都是按照一定顺序连续存储的,而链表则不需要
每个节点都在连续的地址空间中
最后一个节点的指针域总是None self.tail.next=None
头节点永远指向第一个节点
'''
'''
首先定义节点类
'''
class Node(object):
def __init__(self,value=None,next=None):
self.val=value
self.next=next
def __str__(self):
return str(self.val)
'''
再定义链表类
初始化一个链表只需要知道头节点,通过对头节点递归访问
就可以遍历整个链表
一个链表最少要有一个头节点
'''
class LinkedList(object):
def __init__(self,head=None):
'''
:param head: head必须是Node类型
'''
self.head=head
def __len__(self):
# 功能:输入头节点,返回链表长度
counter=0
curr=self.head
while curr is not None:
counter += 1
curr=curr.next
return counter
def insertToFront(self,data):
'''
:param data: data是数值类型
:return: 返回值是插入新数据后的链表的头节点(就是第一个元素/节点)
如果被插入的数据为空,则直接返回
将头节点的next域转换成被插入的节点的next域
将该节点设置为头节点
'''
if data is None:
return None
else:
self.head=Node(data,self.head)
#从这里可以看出,头节点就是第一个节点(Node类型)
return self.head
def append(self,data):
'''
:param data: 如果被插入的数据为空,则直接返回
:return: 将最后一个节点的next域改成当前节点,当前节点的next域为None
'''
if data is None:
return None
else:
if self.head is None:
self.head=Node(data,None)
curr=self.head#找到最后一个节点
while curr.next is not None:
curr=curr.next
last=Node(data,None)
curr.next=last
return last
def find(self,data):
'''
:param data: 数值
:return:
如果所要查找的数据为空,则返回None
将当前节点设置成头节点(头节点是链表中的第一个节点,既有数据域,也有指针域)
如果当前节点为空,则返回None,否则如果当前节点数值等于data,则返回当前节点(Node类型)
否则按顺序向前继续遍历
'''
if data is None:
return None
if self.head is None:
return None
curr=self.head
while curr is not None:
if curr.val==data:
return curr
curr=curr.next
return None
def delete(self,data):
'''
:param data:
:return:
(1)如果所要删除的数据为None,则返回
如果头节点中没有数值,则但会
(2)将头节点设置为前节点,头节点的下一个节点设置为当前节点(当链表中只有一个头节点时,当前节点为None)
判断前节点的数值是否等于data,如果是,则头节点等于头节点的next域,否则,(3)
(3)判断当前节点的数据域是否等于data,如果是则将前节点的next域指向当前节点的next域,否则前节点和当前节点都会向后移动一位
知道当前节点的next域为空为止
'''
if data is None:
return
if self.head is None:
return
if data==self.head.val:
self.head=self.head.next
prev_node=self.head
curr_node=self.head.next
while curr_node is not None:
if curr_node.val==data:
prev_node.next=curr_node.next
return
else:
prev_node=prev_node.next
curr_node=curr_node.next
def delete_alt(self,data):
'''
:param data:
:return:
只定义一个当前节点,如果当前节点的下一个节点数值等于data,则当前节点的next等于后面的节点
当前节点要一直遍历到倒数第二个节点
'''
if data is None:
return
if self.head is None:
return
curr=self.head
if curr.val==data:
self.head=self.head.next
return
while curr.next is not None:
if curr.next.val==data:
curr.next=curr.next.next
return
curr=curr.next
return
leetcode刷题之链表
最新推荐文章于 2023-02-16 23:10:20 发布