【資料結構】棧-數組的實現,資料結構數組實現

來源:互聯網
上載者:User

【資料結構】棧-數組的實現,資料結構數組實現

首先是定義棧的基本結構,因為用數組實現

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了,當然,前提是你代碼中要先申請指標空間才可以。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.