主要的数据结构是:
-
数组
-
链表
-
队列
-
栈
-
散列表
-
树
主要涉及的算法是: -
二分查找
-
选择排序
-
快速排序
-
递归
-
广度优先搜索
-
贪婪算法
-
k邻近算法
数组
在python中以列表形式做数组。一般声明一个数组用,a=[]或a=list()。
区别是,python中的List内可以放置各种数据类型。
list.append() (数值) | 在列表末尾添加一个元素 |
---|---|
list.extend()(列表) | 在列表的末尾添加一个列表 |
list.count()(元素) | 统计该列表中该元素出现几次 |
list.sort(cmp=None, key=None, reverse=False) | 排序,key是指定对谁排序 |
list.remove()(元素) | 移除该列表中第一次出现的这个元素 |
链表
数组的优点在于快速访问,但是由于数组内部存储连续,如果后续添加元素会导致数组的内存溢出。如果提前开辟很大空间给数组就会照成空间浪费。因此,链表结构非常适合经常需要添加数据的状况,因为,其内部存储并不是连续的。链表分为单链表,双链表,单向循环链表。
##一个节点包含两个属性。data是该节点的值,next指向下一个节点
class Node():
def __init__(self,data):
self.data=data
self.next=None
链表常用的内置方法有
class Node():
def __init__(self,data):
self.data=data
self.next=None
class SingleLink():
def __init__(self):
self._head=None###头节点
def is_empty(self):#判断链表是否为空
if self._head==None
return True
else: return False
def add(self,item):#头部添加元素
node=Node(item)
if self.is_empty():
self._head=node
else:
node.next=self._head#新的节点指向头节点指向的位置
self._head=node#头节点指向新的节点
def length(self):#链表长度
if self.is_empty():
return 0
else:
cur=self._head
count=0
while cur!=None
cur=cur.next
count+=1
return count
def append(self,item):#在链表尾部加一个元素
node=Node(item)
if self.is_empty():
self._head=node
else:
cur=self._head
while cur.next!=None:
cur=cur.next
cur.next=node
def search(self,item):#查找列表中是否包含该元素
if self.is_empty():
return No
else:
cur=self._head
while cur!=None:
if cur.data=item:
return Yes
else:
cur=cur.next
return No
def insert(self,pos,item)#pos表示插入的位置,item表示插入的值
node=Node(item)
if pos<=0:
self.add(item)
elif pos>=(self.length()-1)):
self.append(item)
else:
cur=self._head
pre=cur
while pos!=0:
pre=cur
cur=cur.next
pos-=1
node.next=cur
pre.next=node