Python数据结构——图的领结链表法

领结链表法

  1. 时间复杂度n(n+e)
  2. 缺点:增加和删除比较复杂;

代码

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


def create_map(Map):
    array = sorted(set([Map[i][1] for i in range(len(Map))]), reverse=False)
    Map_List = [Node(data) for data in array]

    for head in Map_List:
        ptr = head
        head_data = ptr.data
        for i in range(len(Map)):
            if head_data == Map[i][0]:
                new_node = Node(Map[i][1])
                ptr.next = new_node
                ptr = ptr.next
    return Map_List


def Show_Neibour_List(Map_List):
    for head in Map_List:
        ptr = head
        print(ptr.data, end=" ==> \t")
        ptr = ptr.next
        while ptr:
            print(ptr.data, end="\t")
            ptr = ptr.next
        print()


if __name__ == '__main__':
    Map = [[1, 2], [2, 1], [2, 5], [5, 2], [2, 3], [3, 2], [2, 4], [4, 2], [3, 4], [4, 3], [3, 5], [5, 3], [4, 5],
           [5, 4]]
    map_list = create_map(Map)
    Show_Neibour_List(map_list)


你可能感兴趣的:(链表,数据结构,python)