一、链表基础
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