【資料結構】棧-數組的實現,資料結構數組實現
首先是定義棧的基本結構,因為用數組實現
private String[] stack;private int TOP = 0;
然後是構造方法
StackOfStrings(int capacity) {stack = new String[capacity];}
然後是push,注意,TOP永遠指向的是壓入元素的後一位。
public void push(String str) {if (TOP == stack.length) // if full, increase the stack sizeresize(2 * stack.length);stack[TOP++] = str;}
然後是pop
public String pop() {String popItem = stack[--TOP];// if equal to 1/4, decrease the stack sizeif (TOP > 0 && TOP == stack.length / 4)resize(stack.length / 2);return popItem;}
然後是判空操作,想想為什麼空的時候 TOP是0
public boolean isEmpty() {return TOP == 0;}
最後附上resize的代碼
public void resize(int capacity) {String[] temp = new String[capacity];for (int i = 0; i < TOP; i++)temp[i] = stack[i];stack = temp;}
用數組實現棧與隊列的資料結構
#include <stdlib.h>
#include <stdio.h>
class Stack
{
private:
int ele[100];
int top;
public:
Stack() {
top = 0;
}
void push(int v) {
ele[top++] = v;
}
int pop() {
if(isEmpty()) {
printf("The stack is Empty.\n");
return -1;
}
return ele[--top];
}
bool isEmpty() {
return top == 0;
}
~Stack() {
}
};
#define SIZE 100
class Queue
{
private:
int ele[SIZE];
int head;
int tail;
public:
Queue() {
head = 0;
tail = 0;
}
bool isFull() {
return (tail+1) % SIZE == head;
}
bool isEmpty() {
return head == tail;
}
void enqueue(int val) {
if(isFull()) {
printf("The queue is full, can not enqueue for: %d\n", val);
return;
}
ele[tail] = val;
tail = (tail+1) %SIZE;
}
int dequeue() {
if(isEmpty()) {
printf("The queue is empty, can not dequeue.\n");
return -1;
}
int value = ele[head];
head = (head+1)%SIZE;
return value;
}
};
int main()
{
Stack s;
s.push(123);
s.push(12);
while(!s.isEmpty()) {
printf("%d ", s.pop());
}
printf("\n");
Queue q;
q.enqueue(88);
q.enqueue(13);
q.enqueue(123);
while(!q.isEmpty()) printf("%d ", q.dequeue());
printf("\n");
system("pause");
}...餘下全文>>
資料結構用數組實現棧,下面就是書上給的結構,但是ElementType 到底是個什類型?書上沒有寫
可以是任意類型,你自己定義一個就好了。
如:
typedef ElementType int ; //這樣ElementType *Array;就表示 int *Array;了,你可以按int數組來操作Array了,當然,前提是你代碼中要先申請指標空間才可以。