# python 实现线性链表（单链表）

#!/usr/bin/python
# -*- coding:utf-8 -*-

# Author: Hui
# Date:   2017-10-13

# 结点类，
class Node:

def __init__(self, data):
self.data = data            # 数据域
self.next = None            # 指针域

def get_data(self):
return self.data

# 链表类
class List:

def is_empty(self):         # 空链表判断
return self.get_len() == 0

def get_len(self):          # 返回链表长度
length = 0
while temp is not None:
length += 1
temp = temp.next
return length

def append(self, node):         # 追加结点（链表尾部追加）
while temp.next is not None:
temp = temp.next
temp.next = node

def delete(self, index):           # 删除结点
if index < 1 or index > self.get_len():
print "给定位置不合理"
return
if index == 1:
return
cur_pos = 0
while temp is not None:
cur_pos += 1
if cur_pos == index-1:
temp.next = temp.next.next
temp = temp.next

def insert(self, pos, node):         # 插入结点
if pos < 1 or pos > self.get_len():
print "插入结点位置不合理..."
return
cur_pos = 0
while temp is not Node:
cur_pos += 1
if cur_pos == pos-1:
node.next = temp.next
temp.next =node
break
temp = temp.next

while cur is not None:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre

init_data = []
return init_data

if __name__ == '__main__':

for i in range(1, 10):
node = Node(i)
list.append(node)

print '链表是否空：\t', list.is_empty()

print '链表长度：\t', list.get_len()

list.delete(9)

node = Node("insert")
list.insert(3, node)



• 4
点赞
• 1
评论
• 6
收藏
• 一键三连
• 扫一扫，分享海报

04-06 123

10-16 1807
12-15 861
08-20 937
08-20 105
03-25 357
09-19 149
11-30 3370
03-30 1万+
08-23 8854
07-02 7168