第2章 线性表(5)

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值