抽时间特地将数据结构 一章温习一遍。 看了下清华大学《数据结构》严蔚敏版的数据结构,看的真心很累,一股子浓浓的应试教育的风格扑面而来。实在是难受。 本想将数据结构和算法一起打发,却发现算法环节之精妙,之高深,远非我当前水平能够快速参悟。
秉着先易后难的原则,先把数据结构吃掉还有问题不大。对于链表环节,有时候感觉书上说十遍,还不如自己在编译器上将其描述的数据结构直接创建一次来的直接,干脆,透明,有快感些。 闲话就此打住。直入主题。
栈:
平时看的多,用的少的东西。平日的印象就是FILO , 接触的都是用高级语言——汉语的描述,感悟不是很深。记得看侯捷先生的《深入浅出MFC》,每看一遍都有种新的收获和体验。究其原因:实事求是,用代码说事。
定义栈结构
#include <assert.h>
#include <iostream>
using namespace std;
struct StarkBody; // forward definition
//define the stack head file
struct headPtr
{
unsigned int lenth;
StarkBody *bodyNext;
} ;
// define the stack body struct
struct StarkBody
{
char *Pstr;
StarkBody *Next;
};
使用栈表头
headPtr * NewStack()
{
headPtr *headfile=new headPtr;
headfile->bodyNext=NULL;
headfile->lenth=0;
return headfile;
}
栈操作:进栈和出栈
void Pushing(headPtr *Ptr, const char *data)
{
assert(NULL!=Ptr); //unpredictable enter element protection
assert(NULL!=data);
StarkBody *newdata=new StarkBody;
newdata->Pstr=new char[strlen(data)+1];
memcpy(newdata->Pstr,data,strlen(data)+1);
newdata->Next=Ptr->bodyNext;
Ptr->bodyNext=newdata;
Ptr->lenth++;
}
void Poping(headPtr *Ptr,char *recv)
{
assert(0!=Ptr->lenth);
StarkBody *tmp;
tmp=Ptr->bodyNext;
// modify the stack list
Ptr->bodyNext=tmp->Next;
Ptr->lenth--;
memcpy(recv,tmp->Pstr,strlen(tmp->Pstr)+1);
delete tmp; // delete the pop out item
tmp=NULL; // kill the wild pointer
}
运行 :
int _tmain(int argc, _TCHAR* argv[])
{
headPtr *stack=NULL;
stack=NewStack();
Pushing(stack,"hello");
Pushing(stack,"world");
char *p1=new char[10];
memset(p1 ,0,10);
char *p2=new char[10];
memset(p2,0,10);
Poping(stack,p1);
Poping(stack,p2);
cout<<p1<<" "<<p2<<endl;
int stopped;
cin>>stopped;
return 0;
}
run result :
hello world