目录
一.python变量本质
python中没有为变量赋予类型,所有变量都存储所指向的元素的地址。
在c语言中,会给变量赋予不同的类型。例如int,char,指针等类型。
二.单链表的创建和相关操作
代码
class Node(object):
def __init__(self,elem):
self.elem=elem
self.next=None
class SingleList(object):
def __init__(self,node=None):
self.__head=node
def is_empty(self):
return self.__head==None
def length(self):
cur=self.__head
count=0
while cur!=None:
count+=1
cur=cur.next
return count
def travel(self):
cur=self.__head
while cur!=None:
print(cur.elem,end="\t")
cur=cur.next
print("")
def add(self,item):
node=Node(item)
node.next=self.__head
self.__head=node
def append(self,item):
node=Node(item)
if self.__head==None:
self.__head=node
else:
cur=self.__head
while cur.next!=None:
cur=cur.next
cur.next=node
def insert(self,pos,item):
if pos < 0:
self.add(item)
elif pos>(self.length()-1):
self.append(item)
else:
node=Node(item)
pre=self.__head
count=0
while count<(pos-1):
count+=1
pre=pre.next
node.next=pre.next
pre.next=node
def remove(self,item):
pre=None
cur=self.__head
while cur!=None:
if cur.elem==item:
if cur==self.__head:
self.__head=cur.next
else:
pre.next=cur.next
break
else:
pre=cur
cur=cur.next
def search(self,item):
cur=self.__head
while cur!=None:
if cur.elem==item:
return True
else:
cur=cur.next
return False
if __name__=="__main__" :
ll=SingleList()
print(ll.is_empty())
print(ll.length())
ll.append(1)
print(ll.is_empty())
print(ll.length())
ll.append(2)
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
ll.add(8)
ll.travel()
ll.insert(-1,9)
ll.travel()
ll.insert(3,100)
ll.travel()
ll.insert(10,200)
ll.travel()
node=Node(5)
print(node)
print(ll._SingleList__head)
print("********************************")
ll.remove(9)
ll.travel()
ll.remove(200)
ll.travel()
运行结果
/Users/lichengxiang/Desktop/python/venv/bin/python /Users/lichengxiang/Desktop/python/数据结构和算法/单链表.py
True
0
False
1
8 1 2 3 4 5 6
9 8 1 2 3 4 5 6
9 8 1 100 2 3 4 5 6
9 8 1 100 2 3 4 5 6 200
<__main__.Node object at 0x10454f750>
<__main__.Node object at 0x10454f690>
********************************
8 1 100 2 3 4 5 6 200
8 1 100 2 3 4 5 6进程已结束,退出代码0