단방향 순환 연결 리스트
모든 것을 하나로 연결합니다. 각 노드는 데이터 저장 영역과 링크 영역으로 구분되며, 링크 영역은 다음 노드에 연결됩니다.
항목: 데이터를 저장하려면
next : 다음 노드에 연결
참고: 단방향 순환 연결 목록은 첫 번째 링크입니다. 즉, 꼬리 노드가 헤드 노드에 연결되어야 합니다
단방향 연결 목록 작업
1. 연결리스트가 비어 있는지 여부
2. 연결리스트의 길이
3. 연결리스트 탐색
4. 연결리스트의 선두에 요소 추가
5.
6. 연결리스트의 지정된 위치에 요소를 추가합니다
7. 연결리스트에서 노드를 삭제합니다
8. 노드가 존재하는지 확인합니다
코드 구현
# Functions 函数声明 class Node(): """实例化节点类""" def __init__(self, item): self.item = item self.next = None class Linklist(): """ 存放节点类 """ def __init__(self): self.head = None # 1. 链表是否为空 def is_empty(self): return self.head == None # 2. 链表的长度 def length(self): """ 返回链表的长度 遍历所有的节点,使用计数器计数 1、链表为空情况 """ # 实例化节点 cur = self.head if self.is_empty(): return 0 else: # 计数 count = 1 # 遍历链表 while cur.next != self.head: count+=1 cur = cur.next return count # 3. 遍历链表 def travel(self): """ 遍历链表,获取所有的数据 实例游标,遍历数据,输出数据 1、 空链表情况 2、 只有头部节点情况 3、 只有尾部节点情况 """ # 实例化游标 cur = self.head if self.is_empty(): return None else: # 遍历数据 while cur.next != self.head: print(cur.item, end=' ') cur = cur.next # 最后一个节点要单独输出 print(cur.item) # 4. 链表头部添加元素 def add(self, item): """ 往链表头部添加数据 分析 链表为空 self.head 直接指向node, 再讲node指向自己 链表不为空 node.next = self.head """ # 实例化游标 cur = self.head # 实例化节点 node = Node(item) # 判断是否为空 if self.is_empty(): self.head = node node.next = node else: # 不为空的情况 # 要将最后一个节点指向node while cur.next != self.head: cur = cur.next node.next = self.head self.head = node cur.next = node # 5. 链表尾部添加元素 def append(self, item): """ 往尾部添加数据 分析 实例化节点,再实例化游标先指向最后一个节点 调换指向 1、空链表情况 2、只有一个链表情况 """ # 实例化节点 node = Node(item) # 实例化游标 cur = self.head # 判断是否为空 if self.is_empty(): self.add(item) else: # 不为空的情况,移动游标指向最后一个节点 while cur.next != self.head: cur = cur.next node.next = self.head cur.next = node pass # 6. 链表指定位置添加元素 def insert(self, index, item): """ 指定位置添加数据 实例化节点, 实例化游标指向索引的数据,更改指向 位置大小 链表是否为空 """ # 实例化节点 node = Node(item) # 实例化游标 cur = self.head if index <=0: self.add(item) elif index > (self.length()-1): self.append(item) else: # 判断链表是否为空 if self.is_empty(): self.add(item) else: # 移动游标,指向指定的索引位置 count = 0 while count < index-1: count+=1 cur = cur.next node.next = cur.next cur.next = node pass # 7. 链表删除节点 def remove(self, item): """ 删除指定的节点 实例化游标,遍历链表插件这个节点是否存在,存在则更改指向 不存在,则不修改 空链表情况 头节点情况 尾结点情况 """ # 实例化游标 cur = self.head if self.is_empty(): return None else: # 不为空,遍历链表,对比数据是否相等 # 如果头节点是要删除的数据 if cur.item == item: self.head=cur.next # 找出最后的节点,将最后的节点指向,删除后面的那个节点 while cur.next != self.head: cur = cur.next cur.next = cur.next else: pro = None while cur.next != self.head: if cur.item == item: if cur.item == item: pro.next = cur.next return True else: pro = cur cur = cur.next if cur.item == item: pro.next = self.head pass # 8. 查找节点是否存在 def search(self, item): """ 查找该节点是否存在 实例化游标,遍历所有的节点 查看当前节点的数据是否和item 相等 空链表 头节点 尾结点 """ # 实例化游标 cur = self.head # 判断空链表 if self.is_empty(): return None else: # 不为空遍历整个链表 if cur.item == item: return True else: while cur.next != self.head: if cur.item == item: return True else: cur = cur.next if cur.item == item: return True pass
테스트 실행
# 程序的入口 if __name__ == "__main__": a = Linklist() a.add(400) a.add(300) a.add(200) a.add(100) # a.append(10) a.insert(4,6) # a.remove(6) print(a.length()) # 5 a.travel() # 100 200 300 400 6 print(a.search(100)) # True pass
위 내용은 Python에서 단방향 순환 연결 목록을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Arraysinpython, 특히 비밀 복구를위한 ArecrucialInscientificcomputing.1) theaRearedFornumericalOperations, DataAnalysis 및 MachinELearning.2) Numpy'SimplementationIncensuressuressurations thanpythonlists.3) arraysenablequick

Pyenv, Venv 및 Anaconda를 사용하여 다양한 Python 버전을 관리 할 수 있습니다. 1) PYENV를 사용하여 여러 Python 버전을 관리합니다. Pyenv를 설치하고 글로벌 및 로컬 버전을 설정하십시오. 2) VENV를 사용하여 프로젝트 종속성을 분리하기 위해 가상 환경을 만듭니다. 3) Anaconda를 사용하여 데이터 과학 프로젝트에서 Python 버전을 관리하십시오. 4) 시스템 수준의 작업을 위해 시스템 파이썬을 유지하십시오. 이러한 도구와 전략을 통해 다양한 버전의 Python을 효과적으로 관리하여 프로젝트의 원활한 실행을 보장 할 수 있습니다.

Numpyarrayshaveseveraladvantagesstandardpythonarrays : 1) thearemuchfasterduetoc 기반 간증, 2) thearemorememory-refficient, 특히 withlargedatasets 및 3) wepferoptizedformationsformationstaticaloperations, 만들기, 만들기

어레이의 균질성이 성능에 미치는 영향은 이중입니다. 1) 균질성은 컴파일러가 메모리 액세스를 최적화하고 성능을 향상시킬 수 있습니다. 2) 그러나 유형 다양성을 제한하여 비 효율성으로 이어질 수 있습니다. 요컨대, 올바른 데이터 구조를 선택하는 것이 중요합니다.

tocraftexecutablepythonscripts, 다음과 같은 비스트 프랙티스를 따르십시오 : 1) 1) addashebangline (#!/usr/bin/envpython3) tomakethescriptexecutable.2) setpermissionswithchmod xyour_script.py.3) organtionewithlarstringanduseifname == "__"

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Dreamweaver Mac版
시각적 웹 개발 도구

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

드림위버 CS6
시각적 웹 개발 도구
