class Node():
def __init__(self,value,next=None):
self.value = value
self.next = next
def CreateList(n):
if n<=0:
return False
if n == 1:
return Node(1)
else:
root = Node(1)
tmp = root
for i in range(2,n+1):
tmp.next = Node(i)
tmp = tmp.next
return root
def printList(head):
p = head
while p!=None:
print p.value
p = p.next
def listLen(head):
cnt = 0
p = head
while(p!=None):
p = p.next
cnt += 1
return cnt
def insert(head,n):
if n<1 or n>listLen(head):
return
p = head
for i in range(1,n-1):
p = p.next
a = raw_input("Enter a value:")
t = Node(value = a)
t.next = p .next
p.next = t
return head
def dellist(head,n):
if n<1 or n>listLen(head):
return head
elif n is 1:
head = head.next
else:
p = head
for i in range(1,n-1):
p = p.next
q = p.next
p.next = q.next
return head
def mergeTwoLists(l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
pHead = Node(0)
if l1.value <l2.value:
pHead = l1
pHead.next = mergeTwoLists(l1.next,l2)
else:
pHead = l2
pHead.next = mergeTwoLists(l1,l2.next)
return pHead
if __name__ == "__main__":
print "Create a linklist"
head1 = CreateList(7)
head2 = CreateList(8)
head = mergeTwoLists(head1,head2)
printList(head)
python 模拟链表
最新推荐文章于 2023-12-18 13:52:01 发布