Python实现针对给定单链表删除指定节点的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python实现针对给定单链表删除指定节点的方法。分享给大家供大家参考,具体如下:

题目:

初始化定义一个单链表,删除指定节点,输出链表

下面是具体的实现:

#!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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python对List中的元素排序的方法

首先定义一个compare函数: def compare(sf1, sf2): if (sf1.value > sf2.value): return -1; e...

Python判断字符串是否为字母或者数字(浮点数)的多种方法

str为字符串s为字符串 str.isalnum() 所有字符都是数字或者字母 str.isalpha() 所有字符都是字母 str.isdigit() 所有字符都是数字 str.iss...

Python中的list与tuple集合区别解析

Python中内置了list集合与tuple集合,在list集合中可以实现元素的添加、修改、插入、以及删除。tuple集合看似与list类似,但两者还是有很大的区别。 在tuple集合中...

python使用response.read()接收json数据的实例

如下所示: import json result = response.read() result.decode('utf-8') jsonData = json.loads(r...

详解在Python中以绝对路径或者相对路径导入文件的方法

详解在Python中以绝对路径或者相对路径导入文件的方法

1、在Python中以相对路径或者绝对路径来导入文件或者模块的方法 今天在调试代码的时候,程序一直提示没有该模块,一直很纳闷,因为我导入文件一直是用绝对路径进行导入的。按道理来讲是不会出...