Python实现一个单链表:
"Node.py"
class Node:
"""description of class"""
def __init__(self, val, p=0):
self.data=val;
self.next=p;
"LinkList.py"
from Node import Node
class LinkList:
"""description of class"""
def __init__(self):
self.head=0
def GetLength(self):
p=self.head
len=0
while(p!=0):
len+=1
p=p.next
return len
def Clear(self):
self.head=0
def IsEmpty(self):
if(self.head==0):
return True
else:
return False
def Append(self,item):
q=Node(item)
if(self.head==0):
self.head=q
else:
p=self.head
while(p.next!=0):
p=p.next
p.next=q
def Insert(self, item, index):
if(self.IsEmpty() or index<0):
print "List is empty or Position is error!"
if(index==0):
q=Node(item,self.head)
self.head=q
p=self.head
post=self.head
i=0
while(p.next!=0 and i<index):
post=p
p=p.next
i+=1
if(index==i):
q=Node(item,p)
post.next=q
def GetItem(self,i):
if(self.IsEmpty()):
print "List is empty!"
return
p=self.head
j=0
while(p.next!=0 and j<i):
j+=1
p=p.next
if(j==i):
return p.data
else:
print "The target node is not exist!"
return
def Locate(self,value):
if(self.IsEmpty()):
print "List is Empty"
return -1
p=self.head
i=0
while(not p.data==value and p.next!=0):
i+=1
p=p.next
if p.data==value:
return i
"Program.py"
from Node import Node
from LinkList import LinkList
i=Node(10)
j=Node(9)
k=Node(8)
i.next=j
j.next=k
linklist=LinkList()
linklist.head=i
print linklist.GetLength()
linklist.Append(100)
print linklist.GetLength()
q=linklist.head
while(q!=0):
print q.data
q=q.next
linklist.Insert(10000,2)
q=linklist.head
while(q!=0):
print q.data
q=q.next
print linklist.GetItem(2)
print linklist.Locate(10000)