抽時間特地將數據結構 一章溫習一遍。 看了下清華大學《數據結構》嚴蔚敏版的數據結構,看的真心很累,一股子濃濃的應試教育的風格撲面而來。實在是難受。 本想將數據結構和算法一起打發,卻發現算法環節之精妙,之高深,遠非我當前水平能夠快速參悟。
秉着先易後難的原則,先把數據結構吃掉還有問題不大。對於鏈表環節,有時候感覺書上說十遍,還不如自己在編譯器上將其描述的數據結構直接創建一次來的直接,乾脆,透明,有快感些。 閒話就此打住。直入主題。
棧:
平時看的多,用的少的東西。平日的印象就是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