zoukankan      html  css  js  c++  java
  • 数据结构:链表(五)

    一、链表基础

    1、什么是链表?

    链表中每一个元素都是一个对象,每个对象称为一个节点,包含有数据域key和指向下一个节点的指针next。通过各个节点之间的相互连接,最终串联成一个链表。

    2、节点定义

    class Node(object):
        def __init__(self, data):
            self.data = data
            self.next = None
    
    a = Node(5)
    b = Node(4)
    c = Node(3)
    
    a.next = b
    b.next = c
    
    print(a.next.data)

    打印结果:

    "D:Program FilesPython35python3.exe" E:/test/linklist.py
    4
    
    Process finished with exit code 0

    3、头结点

    二、链表的操作

    1、链表的遍历

    1、图形

     2、代码

    def print_linklist(head):
        node =head
        while node:
            print(node.data)
            node = node.next

    2、链表节点的插入

    1、头插法

    class Node(object):
        def __init__(self, data):
            self.data = data
            self.next = None
    
    
    def create_linklist(li):
        head = None
        for num in li:
            node = Node(num)
            node.next = head
            head = node
        return head
    

    结果

    "D:Program FilesPython35python3.exe" E:test/linklist.py
    6
    5
    4
    3
    2
    1
    
    Process finished with exit code 0

    2、尾插法

    class Node(object):
        def __init__(self, data):
            self.data = data
            self.next = None
    
    
    def create_linklist(li):
        head = None
        for num in li:
            node = Node(num)
            node.next = head
            head = node
        return head
    
    def create_linklist_tail(li):
        head = None
        if not li:
            return head
        head = Node(li[0])
        tail = head
        for num in li[1:]:
            node = Node(num)
            tail.next = node
            tail = node
        return head
    
    def print_linklist(head):
        node =head
        while node:
            print(node.data)
            node = node.next
    
    linklist = create_linklist_tail([1,2,3,4,5,6])
    
    print_linklist(linklist)

    输出:

    "D:Program FilesPython35python3.exe" E:/test/linklist.py
    1
    2
    3
    4
    5
    6
    
    Process finished with exit code 0
    

      

    3、链表节点的删除

    三、双链表的操作

    1、链表节点的插入

    2、链表节点的删除

    四、链表分析

  • 相关阅读:
    python之路---类
    python之路---走台阶(递归)
    python之路---递归函数
    python之路---filter、map、lambda函数
    python之路---封装
    python07--抽象数据类型和python类(P34)
    python06--计算机内存结构与存储管理(P27)
    匹配算法大纲
    并查集及其优化
    Hash技术初涉
  • 原文地址:https://www.cnblogs.com/luoahong/p/9702973.html
Copyright © 2011-2022 走看看