真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

Python實現(xiàn)數(shù)據(jù)結構線性鏈表(單鏈表)算法示例-創(chuàng)新互聯(lián)

本文實例講述了Python實現(xiàn)數(shù)據(jù)結構線性鏈表(單鏈表)算法。分享給大家供大家參考,具體如下:

成都創(chuàng)新互聯(lián)是一家朝氣蓬勃的網(wǎng)站建設公司。公司專注于為企業(yè)提供信息化建設解決方案。從事網(wǎng)站開發(fā),網(wǎng)站制作,網(wǎng)站設計,網(wǎng)站模板,微信公眾號開發(fā),軟件開發(fā),小程序開發(fā),十余年建站對成都VR全景等多個領域,擁有豐富的網(wǎng)站運維經(jīng)驗。

初學python,拿數(shù)據(jù)結構中的線性鏈表存儲結構練練手,理論比較簡單,直接上代碼。

#!/usr/bin/python
# -*- coding:utf-8 -*-
# Author: Hui
# Date:  2017-10-13
# 結點類,
class Node:
  def __init__(self, data):
    self.data = data      # 數(shù)據(jù)域
    self.next = None      # 指針域
  def get_data(self):
    return self.data
# 鏈表類
class List:
  def __init__(self, head):
    self.head = head      # 默認初始化頭結點
  def is_empty(self):     # 空鏈表判斷
    return self.get_len() == 0
  def get_len(self):     # 返回鏈表長度
    length = 0
    temp = self.head
    while temp is not None:
      length += 1
      temp = temp.next
    return length
  def append(self, node):     # 追加結點(鏈表尾部追加)
    temp = self.head
    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:
      self.head = self.head.next
      return
    temp = self.head
    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
    temp = self.head
    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
  def reverse(self, head):     # 反轉鏈表
    if head is None and head.next is None:
      return head
    pre = head
    cur = head.next
    while cur is not None:
      temp = cur.next
      cur.next = pre
      pre = cur
      cur = temp
    head.next = None
    return pre
  def print_list(self, head):      # 打印鏈表
    init_data = []
    while head is not None:
      init_data.append(head.get_data())
      head = head.next
    return init_data
if __name__ == '__main__':
  head = Node("head")
  list = List(head)
  print '初始化頭結點:\t', list.print_list(head)
  for i in range(1, 10):
    node = Node(i)
    list.append(node)
  print '鏈表添加元素:\t', list.print_list(head)
  print '鏈表是否空:\t', list.is_empty()
  print '鏈表長度:\t', list.get_len()
  list.delete(9)
  print '刪除第9個元素:\t',list.print_list(head)
  node = Node("insert")
  list.insert(3, node)
  print '第3個位置插入‘insert'字符串 :\t', list.print_list(head)
  head = list.reverse(head)
  print '鏈表反轉:', list.print_list(head)


當前名稱:Python實現(xiàn)數(shù)據(jù)結構線性鏈表(單鏈表)算法示例-創(chuàng)新互聯(lián)
網(wǎng)站網(wǎng)址:http://weahome.cn/article/dgijde.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部