#!/usr/bin/python
#-*-Coding:utf-8-*-
Class Node (object):
def __init__ (self,val,p=0):
Self.data = Val
Self.next = P
Self.prev = P
Class Linklist (object):
def __init__ (self):
Self.head = 0
def __getitem__ (self, key):
If Self.is_empty ():
print ' linklist is empty. '
Return
Elif key <0 or key > Self.getlength ():
print ' The given key is error '
Return
Else
return Self.getitem (Key)
def __setitem__ (self, Key, value):
If Self.is_empty ():
print ' linklist is empty. '
Return
Elif key <0 or key > Self.getlength ():
print ' The given key is error '
Return
Else
Self.delete (Key)
return Self.insert (Key)
def initlist (Self,data):
Self.head = Node (data[0])
p = Self.head
For i in Data[1:]:
node = node (i)
P.next = node
Node.prev = P
p = P.next
def getlength (self):
p = Self.head
Length = 0
While p!=0:
Length+=1
p = P.next
return length
def is_empty (self):
If Self.getlength () ==0:
Return True
Else
Return False
def clear (self):
Self.head = 0
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
Q.prev = P
def getitem (Self,index):
If Self.is_empty ():
print ' linklist is empty. '
Return
j = 0
p = Self.head
While P.next!=0 and J <index:
p = P.next
J+=1
If J ==index:
Return P.data
Else
print ' target is not exist! '
def insert (Self,index,item):
If Self.is_empty () or index<0 or index >self.getlength ():
print ' linklist is empty. '
Return
If Index ==0:
Q = Node (Item,self.head)
Self.head = q
p = Self.head
Post = Self.head
j = 0
While P.next!=0 and J<index:
Post = P
p = P.next
J+=1
If Index ==j:
Q = Node (item,p)
Post.next = q
Q.prev = Post
Q.next = P
P.prev = q
def delete (Self,index):
If Self.is_empty () or index<0 or index >self.getlength ():
print ' linklist is empty. '
Return
If Index ==0:
Q = Node (Item,self.head)
Self.head = q
p = Self.head
Post = Self.head
j = 0
While P.next!=0 and J<index:
Post = P
p = P.next
J+=1
If Index ==j:
Post.next = P.next
P.next.prev = Post
def index (self,value):
If Self.is_empty ():
print ' linklist is empty. '
Return
p = Self.head
i = 0
While p.next!=0 and not p.data ==value:
p = P.next
I+=1
If P.data = = value:
return I
Else
Return-1
L = linklist ()
L.initlist ([1,2,3,4,5])
Print L.getitem (4)
L.append (6)
Print L.getitem (5)
L.insert (4,40)
Print L.getitem (3)
Print L.getitem (4)
Print L.getitem (5)
L.delete (5)
Print L.getitem (5)
L.index (5)
Same as the single linked list results.