前端学习数据结构之【队列、树】
4.0 Introduction to Queues
Queue ADT:features/operations Stack-Last-In-First
- no implementation details - (LIFO)
- first-In-First-Out
- (FIFO)
(1)EnQueue(x) or Push(x)
(2)DeQueue() or Pop() constant time or O(1)
(3)front() or Peek()
(4)IsEmpty()
Applications:
- printer Queue
- Process Scheduling
- Simulating Wait
4.1 Implementation of Queues
4.1 .1 Array Implementation
int A[10]
int front=-1,rear=-1;
IsEmpty(){
if(front== -1&& rear==-1){
return true
}else{
return false
}
}
EnQueue(x){
//if(rear == A.length-1)return;
if IsFull()return;
else if Isempty()
{
front<-rear<-0;
}
else
{
rear<- rear+1
}
A[rear]<-x;
}
DeQueue()
{
if(IsEmpty())return;
else if front == rear
{
front<-rear<--1
}
else
{
front<-font+1
}
}
//循环队列
EnQueue(x){
if (rear+1)%N == front
return
else if Isempty()
{
front<-rear<-0;
}
else
{
rear<- (rear+1)%N
}
A[rear]<-x;
}
DeQueue(){
if Isempty()
return
else if front == rear
front<- rear <- -1
else
front<- (front+1)%N
}
front(){
return A[front];
}
4.1.2 Linked list Implementation
struct Node{
int data;
struct Node* next;
};
struct Node* front = NULL;
struct Node* rear = NULL;
void Enqueue(int x){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
temp->data = x;
temp->next = NULL;
if(front ==NULL && rear == NULL){
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}
DeQueue(){
struct Node* temp = front;
id(front == NULL)return;
if(front==rear)
{
front = rear = NULL;
}
else
{
front = front->next;
}
free(temp);
}
5.0 Introduction to Trees
- 非线性结构,是层级结构
- binary tree: a tree in which each node can have at most 2 children
struct Node {
int data;
Node* left;
Node* right;
};
Applications:
- storing naturally
hierarchical data ->eg:-file system
- organige data
for quick search,insertion,deletion ->eg:Binary search trees
- Trie -> dictionary
- network routing algorithm
5.1 Binary Tree 二叉树
Binary Tree:each node can have at most 2 children
Strict/Proper binary tree: each node can have either 2 or 0 children
Complete Binary tree:all levels except possibly the last are completely filled and all nodes are as left as possible
5.1.1 height of tree
- min-height=[log2 n] O(log2 n);max-height=n-1 O(n);
5.1.2 binary search Tree
Array 数组已经满,复制的成本是O(n);Linked List BST
search(x) O(n); O(n); O(logn)
Insert(x) O(1); O(1); O(logn)
remove(x) O(n); O(n); O(logn)