一:链表
1、数组是连续的内存空间;而链表可以不一定是连续的内存空间
2、单端链表;从前一个元素指向后一个元素
3、链表的功能
(1)访问 o(n):数组是通过下表或者索引访问元素;链表是通过next指针以此递归的进行查询判断
(2)搜索 o(n):从头部遍历;知道找到位置
(3)插入 o(1):
(4)删除 o(1):
4、特点
写入非常的快;但是读非常的慢{value,next}
5、链表的常用操作
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next#next为指向下一个节点的指针;next=None表示链表为空
class LinkedList:
def __init__(self):
self.head = None#指向链表的第一个节点
# 插入节点到链表的头部
def insert_at_head(self, value):
new_node = ListNode(value)#创建一个新节点;值=value
new_node.next = self.head#将新节点的next指针指向当前的头节点
self.head = new_node#更新链表的头节点
# 插入节点到链表的尾部
def insert_at_tail(self, value):
new_node = ListNode(value)#创建一个新的节点
if not self.head:#如果没有头节点
self.head = new_node#新创建的节点作为头节点
else:
current = self.head#否则遍历链表;找到最后一个节点;将新的节点插入到最后的节点当中
while current.next:
current = current.next
current.next = new_node
# 删除链表中第一个匹配的节点
def delete_node(self, value):
current = self.head
if not current:
return
# 如果要删除的节点是头节点
if current.value == value:
self.head = current.next
return
# 找到要删除的节点并移除它
while current.next:
if current.next.value == value:
current.next = current.next.next
return
current = current.next
# 打印链表
def print_list(self):
current = self.head
while current:
print(current.value, end=" -> ")
current = current.next
print("None")
二:刷题
题目203 移除链表元素
def func(head, val):
k = 0
for i in range(len(head)):
if head[i] != val:
head[k] = head[i]
k += 1
head = head[:k]
return head
# 示例测试
head = [6,5,6,4,6,34,5]
val = 6
flag = func(head, val)
print(flag,end='')
题目206 反转链表
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 集成你想使用的函数,这次实现反转链表
def func(head):
if head is None:
print(head, end="")
return None
prev = None
current = head
while current is not None:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
return func(head)
# 辅助函数:将列表转换为链表
def list_to_linkedlist(lst):
if not lst:
return None
head = ListNode(lst[0])
current = head
for item in lst[1:]:
current.next = ListNode(item)
current = current.next
return head
# 辅助函数:将链表转换为列表
def linkedlist_to_list(node):
result = []
while node:
result.append(node.val)
node = node.next
return result
# 示例测试
head_list = [] # 空列表表示空链表
head = list_to_linkedlist(head_list)
solution = Solution()
reversed_head = solution.reverseList(head)
print(linkedlist_to_list(reversed_head)) # 输出: []
标签:current,head,self,value,next,链表,数据结构
From: https://www.cnblogs.com/gsupl/p/18406822