python --(鏈表)

鏈表的使用node

#/usr/bin/python
#-*- coding: utf-8 -*-
#Function: simulate the link-list in python
#__author__: Tresser
#python

class LNode(object):
  #結點初始化函數, p 即模擬所存放的下一個結點的地址
  #爲了方便傳參, 設置 p 的默認值爲 0
  def __init__(self, data, p=0):
    self.data = data
    self.next = p函數

 

class LinkList(object):
  def __init__(self):
    self.head = None索引

  #鏈表初始化函數, 方法相似於尾插
  def initList(self, data):
    #建立頭結點
    self.head = LNode(data[0])
    p = self.head
    #逐個爲 data 內的數據建立結點, 創建鏈表
    for i in data[1:]:
      node = LNode(i)
      p.next = node
      p = p.nextutf-8

  #鏈表判空
  def isEmpty(self):
    if self.head.next == 0:
      print "Empty List!"
      return 1
    else:
      return 0get

 

  #取鏈表長度
  def getLength(self):
    if self.isEmpty():
      exit(0)it

    p = self.head
    len = 0
    while p:
      len += 1
      p = p.next
    return lenio

 

  #遍歷鏈表
  def traveList(self):
    if self.isEmpty():
      exit(0)
    print '\rlink list traving result: ',
    p = self.head
    while p:
      print p.data,
      p = p.nextclass

 

  #鏈表插入數據函數
  def insertElem(self, key, index):
    if self.isEmpty():
      exit(0)
    if index<0 or index>self.getLength()-1:
      print "\rKey Error! Program Exit."
      exit(0)object

    p = self.head
    i = 0
    while i<=index:
      pre = p
      p = p.next
      i += 1

    #遍歷找到索引值爲 index 的結點後, 在其後面插入結點
    node = LNode(key)
    pre.next = node
    node.next = p

 

  #鏈表刪除數據函數
  def deleteElem(self, index):
    if self.isEmpty():
      exit(0)
    if index<0 or index>self.getLength()-1:
      print "\rValue Error! Program Exit."
      exit(0)

    i = 0
    p = self.head
    #遍歷找到索引值爲 index 的結點
    while p.next:
      pre = p
      p = p.next
      i += 1
      if i==index:
        pre.next = p.next
        p = None
        return 1

    #p的下一個結點爲空說明到了最後一個結點, 刪除之便可
    pre.next = None

 

 


#初始化(創建)鏈表與數據

data = [1,2,3,4,5]

#引用鏈表
l = LinkList()

l.initList(data) #調用(傳值data)鏈表初始化函數 
l.traveList()#調用鏈表遍歷函數 

#(用法例如)插入結點到索引值爲3以後, 值爲666
l.insertElem(666, 3)
l.traveList()#再次調用鏈表遍歷函數

#刪除索引值爲4的結點l.deleteElem(4)l.traveList()

相關文章
相關標籤/搜索