Python은 단일 연결 목록을 구현합니다.

巴扎黑
풀어 주다: 2016-11-26 11:54:18
원래의
1326명이 탐색했습니다.

# 코딩:utf-8 


class Node: 
    def __init__(self, value): 
        self.data = value 
        self.next = None 


class LinkList: 
    def __init__(self, data=[0]): 
        self.head = None 
        self.init_link_list(data) 

    # 初始화链表 
    # data 为数组 
    def init_link_list(self, data): 
        if len(data) == 0: 
            print("초기화 데이터가 null입니다.")             반품 
self.head = Node(data[0]) 
        current = self.head 
        data[1:]의 인덱스용: 
            current.next = Node(index) 
            current = current.next

    # 获取当前结点 
    def get_node(self, index): 
        if self.is_empty(): 
           print("링크가 비어 있습니다") 
            return 
인덱스 > self.get_length() 또는 index <= 0: 
            print("노드가 존재하지 않습니다") 
            return 
        current = self.head 
        i = 0 
        while i < index: 
            if i == index - 1: 
                현재 반환 
            current = current.next 
           i += 1 

    # 获取当前元素的值 
    def get_data (self, index): 
        current = self.get_node(index) 
        current가 None인 경우: 
            "노드가 존재하지 않음" 반환 
        return current.data 

    # 打印链表 
    def print_link(self): 
        if self.is_empty(): 
            return 
        list = [] 
        current = self.head 
        while current.nex t는 없음이 아닙니다:
            list.append(current.data) 
            current = current.next 
        else: 
           list.append(current.data) 
        인쇄(목록)

    # 获取链表长道 
    def get_length(self): 
        if self.is_empty(): 
            return 0 
        current = self.head 
        count = 0 
        current.next가 None이 아닌 동안 : 
            개수 += 1 
            현재 = current.next 
        else: 
            개수 += 1 
        반환 개수 

    #判断链表是否为空 
# 비어 있으면 true를 반환
# 비어 있지 않으면 false를 반환
def is_empty(self):
return self.head is None

# 뒤에 요소 삽입 현재 요소
# 인덱스 요소 인덱스
# 데이터 삽입된 값
def add_after(self, index, data):
current = self.get_node(index)
if current is None:
"노드가 존재하지 않습니다" 반환
current_next = current.next
current.next = Node(data)
current = current.next
current.next = current_next

# 현재
요소 앞에 요소를 삽입합니다. def add_before(self, index, data):
if index == 1:
current = self.get_node(index)
self.head = Node(data)
self.head.next = current
pre.next = Node(data)
          pre = pre.next
pre.next = current

# 가져오기 현재 요소의 이전 요소
def get_pre_node(self, index):
if self.is_empty():
print(" link isempt")
return
if index > .get_length() 또는 index <= 1:
print("노드가 존재하지 않습니다")
pre = self .head
i = 0
while i < index:
if i == index - 2:
return pre
pre = pre.next >          i += 1

#지정된 요소를 삭제하고 삭제된 요소의 값을 반환
def delete( self, index):
index == 1이고 self.is_empty()가 아닌 경우:
data = self.head .data
self.head = self.head.next
return data
pre_node = self.get_pre_node(index)
current = self.get_node(index)
pre_ node가 None이거나 current가 None인 경우:
print("데이터가 존재하지 않습니다")
pre_node. next = current.next
return current.data

# 현재 노드의 값 수정
def update (self, index, data):
current = self.get_node(index)
현재가 None인 경우:
return "current node is none"
current.data = data

# 새 연결 리스트를 현재 연결 리스트에 병합
def merge(self , 데이터):
        size = self.get_length() 
        last_node = self.get_node(size) 
        last_node.next = data.head 
        return self 

# test
y = (1,2 ,3,4) 
s = ["a", "b", "c", "d"] 
linkList = LinkList(y) 
# linkList.init_link_list(["a", " b", "c", "d"]) 
# second = LinkList() 
# second.init_link_list(["x", "y", "z"]) 
# linkList.add_after (-1, "x") 
# linkList.add_after(1, "y") 
# linkList.init_link_list([]) 
# linkList.add_before(1,"x")
# linkList.print_link() 
# print("item:", linkList.get_data(2)) 
# print("length:", linkList.get_length()) 
# print("is 비어 있음 ", linkList.is_empty()) 
# print(linkList.get_pre_node(3).data) 
# print("remove node:",linkList.remove(2)) 
# linkList.merge( 두 번째) 


linkList.print_link() 

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!