10-02-2009, 14:28
|
מנהל פורומי "תכנות ובניית אתרים" ו"חומרה ורשתות"
|
|
חבר מתאריך: 25.10.01
הודעות: 42,775
|
|
קוד ++C שלי שמניח שהמחסנית ממומשת באמצעות פונקציות על רשימה משורשרת (כמו בדוגמא שנתתי לעיל...) - הקוד מממש רק שתי פונקציות - הוספה למחסנית (ויצירתה אם אינה קיימת) - ובדיקת גודל המחסנית:
אם זה עוזר, יופי, אם לא... סורי, זה מה שאני יודע...
קוד PHP:
#include <iostream>
using namespace std;
struct stackType {
int mydata;
stackType *previous;
};
int counter = 0; // stack counter
stackType* stackPush(stackType *topStack, int value)
{
stackType *temp;
if (topStack == NULL)
{
topStack = new stackType;
topStack->previous = NULL;
topStack->mydata = value;
cout << "Empty stack, creating a new stack and using " << value << " as first value..." << endl;
}
else
{
cout << "Stack has at least one item, adding " << value << " to stack..." << endl << endl;
temp = topStack;
topStack = new stackType;
topStack->previous = temp;
topStack->mydata = value;
}
return topStack;
}
int stackSize(stackType *topStack)
{
if (topStack == NULL)
return -1;
else
counter++;
stackSize(topStack->previous);
return counter;
}
int main ()
{
stackType *topStack;
topStack = NULL;
for (int i=0; i<10; i++)
{
cout << "Putting " << i << " into stack... " << endl;
topStack = stackPush(topStack, i);
}
cout << "Now I'll count how many values I have in my stack and print that... the size of the stack is: "
<< stackSize(topStack) << " (-1 means no stack!)" << endl
<< "Program finished." << endl;
return 0;
}
|