本文实例讲述了Python实现针对给定单链表删除指定节点的方法。分享给大家供大家参考,具体如下:
题目:
初始化定义一个单链表,删除指定节点,输出链表
下面是具体的实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
#!usr/bin/env python #encoding:utf-8 ''''' __Author__:沂水寒城 功能:给定一个单链表删除指定节点 ''' class Node( object ): ''''' 节点类 ''' def __init__( self ,data): self .num = data self . next = None class DeleteNode(): ''''' 实现删除指定节点功能 ''' def delete_node( self ,node): node.num = node. next .num node. next = node. next . next class PrintNode(): ''''' 输出指定节点为起始节点的链表 ''' def print_node( self ,node): res_list = [] while node: res_list.append( str (node.num)) node = node. next print '->' .join(res_list) if __name__ = = '__main__' : node1 = Node( 90 ) node2 = Node( 34 ) node3 = Node( 89 ) node4 = Node( 77 ) node5 = Node( 23 ) node1. next = node2 node2. next = node3 node3. next = node4 node4. next = node5 print 'init single linknode is:' printnode = PrintNode() printnode.print_node(node1) delete = DeleteNode() delete.delete_node(node4) print 'after delete node,the single linknode is:' printnode.print_node(node1) |
结果如下:
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/together_cz/article/details/77493916