数据结构:链表(五)

一、链表基础

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 Files\Python35\python3.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 Files\Python35\python3.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 Files\Python35\python3.exe" E:/test/linklist.py
1
2
3
4
5
6

Process finished with exit code 0

  

3、链表节点的删除

三、双链表的操作

1、链表节点的插入

2、链表节点的删除

四、链表分析

 

posted @ 2018-09-25 19:42  活的潇洒80  阅读(169)  评论(0编辑  收藏  举报