前端学习数据结构之【数组、链表】
Applications menory
Applications menory are made by 4 component。
Heap 动态存储,我们无法再栈上控制内存的分配和释放
Stack 局部变量,还有关于函数调用的所有信息,main函数,函数里面的变量
Static/Global 全局变量区
Code(Text)
Introduction to stacks
stack ADT: A list with the restriction that insertion and deletion can be pertormed only from one end, clled the top.
- List item只能访问栈顶
- Operations: Push(x)\Pop()\Top()\IsEmpty(),constant time or O(1)
- Applications:
- Function calls/Recursion 递归
- undo in an editor 编辑器
- Balanced Parentheses 算法
Implementation of stacks
- Array implementation
//Stack - Array based implementation
#include<stion.h>
#define MAX_SIZE 101
int A[MAX_SIZE];
int top = -1;
void push(int x){
if(top == MAX_SIZE -1){
printf("Error: no size to push\n")
return;
}
A[++top] = x;
}
void pop(){
if(top == -1){
printf("Error: no element to pop\n")
return;
}
top--;
}
int Top(){
return A[top];
}
void Print(){
int i;
for(i =0;i<=top;i++){
printf("%d",A[i]);
}
printf("\n");
}
int main(){
Push(2);
Push(5);
pop();
Push(10);
}
doubly linked list implementation
#include<stdio.h>
#include<stdib.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
}
struct Node* head;//global variable- pointer to head node.
struct Node* GetNewNode(int x){
//local variable
//will be cleared from menory when function call will finish.
// struct Node myNode;
// myNode.data = x;
// myNode.prev = NULL;
// myNode.next = NULL;
//return &newNode;
// so
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
(*newNode).data = x;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void InsertAtHead(int x){
struct Node* newNode = GetNewNode(x);
if(head == NULL){
head = newNode;
return;
}
head->pre = newNode;//pre data pointer
newNode->next = head;
head = newNode;
}
void Print(){
struct Node* temp = head;
if(temp == NULL)return;//empty list,exit
printf("Reverse:");
while(temp!= NULL){
printf("%d",temp->data);
temp = temp->next;
}
printf("\n");
}
void ReversePrint(){
struct Node* temp = head;
if(temp == NULL)return;//empty list,exit
//Going to last Node
while(temp->next != NULL){
temp = temp->next;
}
//Traversing backward using prev pointer
printf("Reverse:");
while(temp!= NULL){
printf("%d",temp->data);
temp = temp->prev;
}
printf("\n");
}
int main(){
head = NULL;
InsertAtHead(2);Print();ReversePrint();
InsertAtHead(4);Print();ReversePrint();
InsertAtHead(6);Print();ReversePrint();
}