Codes for Job Hunt

2010-12-26 wcdj

Some codes for job hunt are post here.

 

[1] Binary Tree /* PreCreateBTree, PostDestroyBTree, BTreePreOrder, BTreeHeight, BTreeLeafnodeNum, BTreeSwap */ #include <iostream> #include <string> using namespace std; // the data struct of the binary tree node typedef char datatype; typedef struct node { datatype data; struct node *lchild, *rchild; }BTree; // build binary tree BTree *PreCreateBTree(const char * sztree) { static size_t i=-1,len=strlen(sztree); while (++i != len) { if (sztree[i]=='#')// null node { return NULL; } else { //BTree *newnode=(BTree *)malloc(sizeof(BTree));// C BTree *newnode=new BTree;// C++ if (newnode==NULL) { cout<<"error: new BTree"<<endl; return NULL; } newnode->data=sztree[i]; newnode->lchild=PreCreateBTree(sztree);// left child tree newnode->rchild=PreCreateBTree(sztree);// right child tree return newnode; } } } // postorder to delete the binary tree void DestoryBTree(BTree *bt) { if (bt==NULL) { return; } else { DestoryBTree(bt->lchild); DestoryBTree(bt->rchild); //free(bt);// C delete bt;// C++ } } // preorder void BTreePreOrder(BTree *bt) { if (bt) { cout<<bt->data<<" "; BTreePreOrder(bt->lchild); BTreePreOrder(bt->rchild); } } // calculate the height of binary tree #define MAX(x,y) (x>y?x:y) int BTreeHeight(BTree *bt) { if (bt==NULL) { return 0; } return MAX(BTreeHeight(bt->lchild),BTreeHeight(bt->rchild))+1; } // calculate the number of the leaf node int BTreeLeafnodeNum(BTree *bt) { if (bt==NULL) { return 0; } if (bt->lchild==NULL && bt->rchild==NULL) { return 1; } else { return BTreeLeafnodeNum(bt->lchild)+BTreeLeafnodeNum(bt->rchild); } } // swap the lchild for rchild #define SWAP(x,y,tmp) do / {/ tmp=x;/ x=y;/ y=tmp;/ } while (0)/ void BTreeSwap(BTree *bt) { BTree *tmp=NULL; if (bt) { BTreeSwap(bt->lchild); BTreeSwap(bt->rchild); SWAP(bt->lchild,bt->rchild,tmp); } } int main() { string str; cout<<"Enter a preorder of binary tree and use '#' stands for a null node to build the tree: "<<endl; cin>>str; // build BTree *bt=PreCreateBTree(str.c_str()); if (bt==NULL) { cout<<"there are something wrong with building a binary tree !"<<endl; return EXIT_FAILURE;// 1 } // print preorder cout<<"the preorder of binary tree is: "<<endl; BTreePreOrder(bt); cout<<endl; // print the height of the binary tree int height=BTreeHeight(bt); cout<<"the binary tree's height is: "<<height<<endl; // print the number of the binary tree int leafnum=BTreeLeafnodeNum(bt); cout<<"the number of binary tree' leaf node is: "<<leafnum<<endl; // swap the binary tree cout<<"after swap, the preorder of binary tree is: "<<endl; BTreeSwap(bt); BTreePreOrder(bt); cout<<endl; // when not using it we need to delete it DestoryBTree(bt); return EXIT_SUCCESS;// 0 } [2] read the data from the file and write the sorted data into the file. #include <iostream> #include <string> #include <vector> #include <fstream> using namespace std; void BubbleSort(vector<int> &ivec) { vector<int>::size_type count=ivec.size(); bool bswap=false; for (int i=count-1; i!=0; --i ) { for (int j=count-1; j!=count-i-1; --j) { if (ivec[j]<ivec[j-1]) { //SWAP(ivec[j-1],ivec[j]); ivec[j-1]^=ivec[j]; ivec[j]^=ivec[j-1]; ivec[j-1]^=ivec[j]; // mark bswap=true; } } if (!bswap) { break; } } } int main() { // read data from the file ifstream ifs; string str="c://data.txt"; ifs.open(str.c_str()); if (!ifs) { cerr<<"unable to open the input file: "<<str<<endl; return EXIT_FAILURE; } vector<int> ivec; int tmp; // ok while (ifs>>tmp) { ivec.push_back(tmp); } // error, add the last element twice! //while (!ifs.eof()) //{ // ifs>>tmp; // ivec.push_back(tmp); //} ifs.close(); ifs.clear(); // sort BubbleSort(ivec); // write the sorted data into the file ofstream ofs; ofs.open(str.c_str()); if (!ofs) { cerr<<"unable to open the file: "<<str<<endl; return EXIT_FAILURE; } for (vector<int>::const_iterator iter=ivec.begin(); iter!=ivec.end(); ++iter) { ofs<<*iter<<" "; } ofs.close(); return 0; } [3] LinkList /* CreateHeadLinkList, CreateNoHeadLinkList, PrintHeadLinkList, PrintNoHeadLinkList ReverseList, GetNodeDataByNum, GetNodePointerByNum, DeleteNodeByNum, InsertNodeAfterPointer, BubbleSort */ #include <iostream> using namespace std; #define NULL 0 typedef char datatype; typedef struct Node { datatype data; struct Node *next; }LNode, *LinkList; // create a LinkList head node // insert the new node from the last node LinkList CreateHeadLinkList() { LinkList head=(LinkList)malloc(sizeof(LNode)); if (!head) { cerr<<"error: malloc head node! "<<endl; return NULL; } head->data=NULL; head->next=NULL; cout<<"create the head node"<<endl; cout<<"enter the data of node (# to end): "<<endl; LinkList node=NULL; LinkList cur=head; char ch; while (cin>>ch) { if (ch=='#') { break; } // create a new node node=(LinkList)malloc(sizeof(LNode)); if (!node) { cerr<<"error: malloc new node! "<<endl; return NULL; } node->data=ch; node->next=NULL; // insert the new node into the LinkList cur->next=node; cur=node; cout<<"insert a new node into the LinkList"<<endl; } cin.clear(); return head; } // create a LinkList without head node // insert the new node as the first node LinkList CreateNoHeadLinkList() { cout<<"enter the data of node (# to end): "<<endl; LinkList node=NULL; LinkList curhead=NULL;// the first node, that is the last node in the LinkList char ch; while (cin>>ch) { if (ch=='#') { break; } // create a new node node=(LinkList)malloc(sizeof(LNode)); if (!node) { cerr<<"error: malloc new node! "<<endl; return NULL; } node->data=ch; // insert the new node into the LinkList node->next=curhead; curhead=node;// mark the current head node cout<<"insert a new node into the front of LinkList"<<endl; } cin.clear(); return curhead; } // print the LinkList with head node void PrintHeadLinkList(LinkList head) { if (head==NULL || head->next==NULL) { cout<<"the LinkList is NULL"<<endl; return; } LinkList cur=head->next; while (cur) { cout<<cur->data<<" "; cur=cur->next; } cout<<endl; } // print the LinkList without head node void PrintNoHeadLinkList(LinkList curhead) { if (curhead==NULL) { cout<<"the LinkList is NULL"<<endl; return; } LinkList cur=curhead; while (cur) { cout<<cur->data<<" "; cur=cur->next; } cout<<endl; } // reverse the LinkList void ReverseList(LinkList &head) { if (head==NULL || head->next==NULL) { cout<<"the LinkList is NULL"<<endl; return; } LinkList pfirst=head,psecond=pfirst->next,pthird=psecond->next; pfirst->next=NULL; while (pthird) { psecond->next=pfirst; pfirst=psecond; psecond=pthird; pthird=pthird->next; } psecond->next=pfirst; head=psecond; } // delete the LinkList void DeleteLinkList(LinkList head) { LinkList tmp=NULL; while (head) { tmp=head; head=head->next; free(tmp); } cout<<"delete LinkList"<<endl; } // get the data from some node by number datatype GetNodeDataByNum(LinkList head, int num) { if (head==NULL) { cout<<"the LinkList is NULL"<<endl; return NULL; } int i=0; while (head) { ++i; if (i==num) { return head->data; } head=head->next; } cout<<"there is no this number"<<endl; return NULL; } // get the pointer of node by number LinkList GetNodePointerByNum(LinkList head,int num) { if (head==NULL) { cout<<"the LinkList is NULL"<<endl; return NULL; } int i=0; while (head) { ++i; if (i==num) { return head; } head=head->next; } //cout<<"there is no this number"<<endl; return NULL; } // delete the node by number LinkList DeleteNodeByNum(LinkList head,int n) { if (head==NULL) { cout<<"the LinkList is NULL"<<endl; return NULL; } LinkList p=GetNodePointerByNum(head,n); if (p==head)// only one node { return head; } LinkList front=GetNodePointerByNum(head,n-1); if (p->next==NULL)// the last node { front->next=NULL; return p; } else { front->next=p->next; return p; } } // insert the node void InsertNodeAfterPointer(LinkList &head,LinkList p,LinkList pDele) { if (p==NULL)// the only one head node before pDele node { pDele->next=head; head=pDele; } else { pDele->next=p->next; p->next=pDele; } } // bubble sort void BubbleSort(LinkList &head) { // calculate the length of the LinkList int len=0; LinkList tmp=head; while (head) { ++ len; head=head->next; } head=tmp; for (int i=len-1; i!=0; --i) { bool mark=false; for (int j=len; j!=len-i; --j) { if (GetNodeDataByNum(head,j-1)>GetNodeDataByNum(head,j)) { // swap=delete+insert LinkList pDele=DeleteNodeByNum(head,j);// three cases LinkList p=GetNodePointerByNum(head,j-2); InsertNodeAfterPointer(head,p,pDele); mark=true; } } if (!mark) { break; } } } int main() { LinkList head=CreateHeadLinkList(); PrintHeadLinkList(head); LinkList nohead=CreateNoHeadLinkList(); PrintNoHeadLinkList(nohead); // sort the data cout<<"after bubblesort, the data is: "<<endl; BubbleSort(head);// delete+insert PrintHeadLinkList(head); // sort the data cout<<"after bubblesort, the data is: "<<endl; BubbleSort(nohead);// delete+insert PrintNoHeadLinkList(nohead); // reverse the LinkList ReverseList(head); PrintNoHeadLinkList(head);// note after reversing, the LinkList has no head node ReverseList(nohead); PrintNoHeadLinkList(nohead); // when not using to delete the LinkList DeleteLinkList(head); DeleteLinkList(nohead); return 0; } [4] 实现四则运算表达式 /* 四则运算表达式 1. 如果是运算量,则直接写入数据队列 2. 如果是左括号"(",则直接压入符号栈; 3. 如果是右括号")",则不断弹出符号栈数据,并写入数据队列,直到左括号弹出; 4. 如果是普通运算符,则与栈顶符号比较优先级,如果大于栈顶符号优先级,则入栈; 否则弹出栈顶符号并写入数据队列,直到栈顶符号的运算符优先级较小为止,并且将当前运算符压入栈中; 5. 如果是结束符(表示表达式已全部读完),则符号栈全部弹出并写入存储器,否则读取数据进入下个过程。 */ #include <iostream> #include <string> #include <stack> #include <queue> using namespace std; int RetSymbol(char c) { int nRet = 0; switch (c) { case '#': nRet = 0; break; case '+': nRet = 3; break; case '-': nRet = 3; break; case '*': nRet = 4; break; case '/': nRet = 4; break; default: break; } return nRet; } double Operate(double a, double b, char c) { double nRet = 0.0; switch (c) { case '+': nRet = a + b; break; case '-': nRet = a - b; break; case '*': nRet = a * b; break; case '/': nRet = a / b; break; } return nRet; } int main(void) { stack<char> stackSymbol; //放置运算符的栈 queue<char> queueData; //放置运算数据的队列 stack<double> RetData; //放置最终运算结果的栈 string strExpress; //需要计算的表达式 cin>>strExpress; const char *pTemp = strExpress.c_str(); stackSymbol.push('#'); while (*pTemp) { if (*pTemp >= '1' && *pTemp <= '9') { //如果为运算数据,直接存入运算数据队列 queueData.push(*pTemp); } else if (*pTemp == '(') { //如果为左括号,直接入栈 stackSymbol.push(*pTemp); } else if (*pTemp == ')') { //如果为右括号,则按照规则将运算符出栈。 while (stackSymbol.top() != '(') { char temp = stackSymbol.top(); stackSymbol.pop(); queueData.push(temp); } stackSymbol.pop(); } else { //如果为普通四则运算符,则按照规则入栈和出栈 while (RetSymbol(*pTemp) <= RetSymbol(stackSymbol.top()))// { char temp = stackSymbol.top(); stackSymbol.pop(); queueData.push(temp); } stackSymbol.push(*pTemp); } ++pTemp; } while (!stackSymbol.empty()) { //将运算符栈中所有剩余的运算符都弹出到运算数据队列中 char temp = stackSymbol.top(); stackSymbol.pop(); queueData.push(temp); } //打印逆波兰式 int nSize = queueData.size(); queue<char> queueTemp = queueData; for (int i = 0; i < nSize; ++i) { printf("%c", queueTemp.front()); queueTemp.pop(); } cout<<endl; //下面开始计算表达式的值 double nLeft = 0.0, nRight = 0.0; while(queueData.size() > 1.) { if (queueData.front() >= '1' && queueData.front() <= '9' ) { double nTemp = queueData.front() - 48; RetData.push(nTemp); queueData.pop(); } else if (queueData.front() != '#') { nLeft = RetData.top(); RetData.pop(); nRight = RetData.top(); RetData.pop(); char cTemp = queueData.front(); double nTemp = Operate(nRight, nLeft, cTemp); RetData.push(nTemp); queueData.pop(); } } cout<<strExpress<<"="<<RetData.top()<<endl; return 0; } 问题:实现整数的四则运算(+,-,*,/) 分析:首先把四则运算的字符串转换成后缀表达式(逆波兰式)保存在栈A中,然后获取栈顶元素,如果是数字则保存到另一个栈B中,如果是运算符(+,-,*,/)就从栈B中依次获取栈顶两个操作数进行运算,运算结果再压栈B,如此反复,最终栈B中最后的值就是运算结果。 // arithmetic.h #include <stdio.h> #include <malloc.h> #include <string.h> #include <stdlib.h> #include "Stack.h" class Data { public: double num; char op; }; class Arithmetic { private: DoubleStack dStack; //保存四则运算时,后缀表达式中的操作数 CharStack cStack; //保存中缀表达式转换成后缀表达式过程中的操作符 int isp(char op); //栈内优先级 int icp(char op); //栈外优先级 public: Data post[100]; //保存后缀表达式 int curLen; //后缀表达式数组的实际长度 void midTopost(char *c); //把中缀表达式转换成后缀表达式 double calculate(); //进行四则运算 }; // Stack.h #include <stdio.h> #include <malloc.h> //栈节点数据结构 class DoubleNode { friend class DoubleStack; private: double value; DoubleNode *next; //构造函数 DoubleNode(double value, DoubleNode *p):value(value),next(p){} }; //栈,用来保存采用后缀表达式进行四则运算时的操作数 class DoubleStack { private: DoubleNode *top; public: DoubleStack():top(NULL){} ~DoubleStack(); void push(double value); double pop(); bool isEmpty(){return top == NULL;} double getTop(); }; //栈节点数据结构 class CharNode { friend class CharStack; private: char value; CharNode *next; //构造函数 CharNode(char value, CharNode *p):value(value),next(p){} }; //栈,用来保存中缀表达式转换成后缀表达式时的运算符 class CharStack { private: CharNode *top; public: CharStack():top(NULL){} ~CharStack(); void push(char value); char pop(); bool isEmpty(){return top == NULL;} char getTop(); void makeEmpty(); }; // arithmetic.cpp #include "arithmetic.h" void Arithmetic::midTopost(char *c) { int i = 0; int k; int j; char tmp; char a[100]; char num[10]; //下面开始把字符串中的操作符(+-*/)放入后缀表达式 cStack.makeEmpty(); cStack.push('#'); //字符串最后都加一个# strcat(c, "#"); k = 0; while (c[k] != '/0') { if (c[k] == '+' || c[k] == '-' || c[k] == '*' || c[k] == '/' || c[k] == '(') { //如果优先级低,一直退栈,否则入栈 while (isp(cStack.getTop()) > icp(c[k])) { post[i++].op = cStack.pop(); } cStack.push(c[k]); } else if (c[k] == ')') { //一直退栈到'(' while (isp(cStack.getTop()) >= icp(')')) { tmp = cStack.pop(); if (tmp != '(') { post[i++].op = tmp; } } } else if (c[k] == '#') { while (isp(cStack.getTop()) > icp('#')) { tmp = cStack.pop(); post[i++].op = tmp; } } else if (c[k] >= '0' && c[k] <= '9') { //数字,继续往后获取字符,如果是数字,全部拼装到num中,然后转换成double类型 j = 0; memset(num, 0, 10); num[j] = c[k]; k = k + 1; while (c[k] >= '0' && c[k] <= '9') { num[++j] = c[k]; k++; } post[i].num = atof(num); post[i].op = '#'; i++; k--; } else { //其他非法字符,不处理 } k++; } curLen = i; } //栈内优先级,栈内优先级大于栈外优先级 //'('的栈内优先级应该比所有的操作符都小(除了#) //')'的栈内优先级应该最大 //+-的优先级一致,*/的优先级一致 int Arithmetic::isp(char op) { int pri; switch (op) { case '#' : pri = 0; break; case '(' : pri = 1; break; case '+' : pri = 3; break; case '-' : pri = 3; break; case '*' : pri = 5; break; case '/' : pri = 5; break; case ')' : pri = 10; break; } return pri; } //栈外优先级 int Arithmetic::icp(char op) { int pri; switch (op) { case '#' : pri = 0; break; case '(' : pri = 10; break; case '+' : pri = 2; break; case '-' : pri = 2; break; case '*' : pri = 4; break; case '/' : pri = 4; break; case ')' : pri = 1; break; } return pri; } //根据后缀表达式进行四则运算 double Arithmetic::calculate() { int i; double result = 0; double left, right; for (i = 0; i < curLen; i++) { //如果是数字就入栈 if (post[i].op == '#') { dStack.push(post[i].num); } else //如果是操作符,就取出两个数字进行运算 { right = dStack.pop(); left = dStack.pop(); switch (post[i].op) { case '+' : dStack.push(left + right); break; case '-' : dStack.push(left - right); break; case '*' : dStack.push(left * right); break; case '/' : dStack.push(left / right); break; } } } return dStack.pop(); } // Stack.cpp #include "Stack.h" DoubleStack::~DoubleStack() { DoubleNode *p; while (NULL != top) { p = top; top = top->next; delete p; } } void DoubleStack::push(double value) { top = new DoubleNode(value,top); } double DoubleStack::pop() { if (!isEmpty()) { DoubleNode *p; p = top; top = top->next; double nodeValue = p->value; delete p; return nodeValue; } } double DoubleStack::getTop() { return top->value; } CharStack::~CharStack() { CharNode *p; while (NULL != top) { p = top; top = top->next; delete p; } } void CharStack::push(char value) { top = new CharNode(value,top); } char CharStack::pop() { if (!isEmpty()) { CharNode *p; p = top; top = top->next; char nodeValue = p->value; delete p; return nodeValue; } } void CharStack::makeEmpty() { CharNode *p; while (NULL != top) { p = top; top = top->next; delete p; } } char CharStack::getTop() { return top->value; } // main.cpp #include "arithmetic.h" int main() { char tmp[100]; printf("please input a arithmetic express:/n"); scanf("%s", tmp); Arithmetic ari = Arithmetic(); ari.midTopost(tmp); printf("the result = [%f]/n", ari.calculate()); getchar(); } [5] 约瑟夫环 /* 设有顺序编号为至n的n个人,按顺时针顺序站成一个圆圈。首先从第一个人开始, 从开始顺时针报数,报到第m(<n)个人,令其出列。然后再从出列的下一个人开始, 从顺时针报数,报到第m个人,再令其出列,……,如此下去,直到圆圈不再有人为止。 求这n个人出列顺序。 */ // 数组的方法 #include <iostream> using namespace std; typedef struct People { int num; bool mark;// 0 and 1, 1 stands for out }ppl; int main() { // initialize cout<<"Enter n and m (m<n): "<<endl; int n,m; cin>>n>>m; ppl *szPeople=new ppl[n]; for (int i=0; i!=n; ++i) { szPeople[i].num=i+1; szPeople[i].mark=false; } // print every people int count=0; int time=0; while (1) { for (int i=0; i!=n; ++i) { if (szPeople[i].mark==true)// this has been out, go to the next { continue; } else { ++count; } if (count==m) { cout<<szPeople[i].num<<" "; ++time; szPeople[i].mark=true; count=0; } } if (time==n) { break; } } cout<<endl; // delete delete []szPeople; return 0; } // 数组的方法2 (数组中元素初始化为~n,为表示此人out) #include <iostream> using namespace std; int main() { // initialize cout<<"Enter n and m (m<n): "<<endl; int n,m; cin>>n>>m; int *szPeople=new int[n]; for (int i=0; i!=n; ++i) { szPeople[i]=i+1; } // print every people int count=0; int time=0; while (1) { for (int i=0; i!=n; ++i) { if (szPeople[i]==0)// this has been out, go to the next { continue; } else { ++count; } if (count==m) { cout<<szPeople[i]<<" "; ++time; szPeople[i]=0;// mark this man has been out count=0; } } if (time==n) { break; } } cout<<endl; // delete delete []szPeople; return 0; } // 链表的方法 #include <iostream> using namespace std; typedef struct Node { int num; struct Node *next; }LNode,* LinkList; // make loop LinkList, return the last pointer LinkList MakeLoop(int n) { LinkList head, tail, p; head=tail=p=NULL; for (int i=1; i!=n+1; ++i) { p=(LinkList)malloc(sizeof(LNode)); if (p==NULL) { cerr<<"error: malloc node"<<endl; return NULL; } p->num=i; if (head==NULL) { head=tail=p; head->next=NULL; } else { tail->next=p; tail=p; } } // make loop tail->next=head; return head; } int main() { cout<<"Enter n and m (n>m): "<<endl; int n,m; cin>>n>>m; // special case if (m==1) { for (int i=1; i!=n+1; ++i) { cout<<i<<" "; } cout<<endl; } // initialize LinkList head=MakeLoop(n); LinkList p=head, cur=NULL; while (p) { for (int i=1; i!=m-1; ++i) { p=p->next; } cur=p->next;// cur mark the m_th node cout<<cur->num<<" "; // delete this node p->next=cur->next; p=p->next;// next node if (p==cur)// the last node { p=NULL; } free(cur); cur=NULL; } cout<<endl; return 0; } [6] memcpy, memmove #include <cstdio> #include <string.h> // memcpy库函数头文件 #include <conio.h> // getch头文件 #include <assert.h> //assert头文件 typedef unsigned char byte; //typedef unsigned int size_t; /* memcpy自定义函数 */ //src要保留 void* memcpy(void* dst,const void* src,size_t count) { char* pbTo = (char*)dst; char* pbFrom = (char*)src; assert(dst!= NULL && src != NULL);//不能存在空指针 assert(pbTo >= pbFrom+count || pbFrom >= pbTo + count);//防止内存重叠(overlap) while (count-- > 0) { *pbTo++ = *pbFrom++; } return dst; } /* memmove自定义函数 */ //src可以不保留 void* memmove(void* dst,const void* src,size_t count) { char* pbTo = (char*)dst; char* pbFrom = (char*)src; assert(dst != NULL && src != NULL);//不能存在空指针 if (dst <= src || pbTo >= pbFrom + count)//没有overlap的情况,直接拷贝 { while (count-- > 0) { *pbTo++ = *pbFrom++; } } else { pbTo = pbTo + count -1;//overlap的情况,从高位地址向低位拷贝 pbFrom = pbFrom + count -1; while (count-- > 0) { *pbTo-- = *pbFrom--; } } return dst; } int main() { // test char src[]="123456"; char dst[]="abcdefghijklmnopqrstuvwxyz"; char *ptr; printf("destination before memcpy: %s/n",dst); //测试用例 ptr=(char *)memcpy(dst,src,sizeof(src)/sizeof(char));// "123456" //ptr=(char *)memcpy(dst,src,strlen(src));// "123456ghijklmnopqrstuvwxyz" //测试用例 //ptr=(char *)memmove(dst,src,sizeof(src)/sizeof(char));// "123456" //ptr=(char *)memmove(dst,src,strlen(src));// "123456ghijklmnopqrstuvwxyz" //测试用例 //ptr=(char *)memcpy(dst+1,dst,2);//memcpy没有考虑内存覆盖,如果出现覆盖assert报错 //测试用例 //ptr=(char *)memmove(dst+1,dst,2);//memmove考虑了内存覆盖"abde...z" if (ptr) { printf("destination after memcpy: %s/n",ptr); } else { printf("memcpy failed/n"); } getch(); return 0; } [7] strcpy // 最简单的写法 char *strcpy(char *dest, const char *src) { char *save = dest; while(*dest++ = *src++);//加上!='0',纯粹是脱裤子放屁--多此一举。 return save; } // 稍复杂点儿的写法 char *strcpy(char *dest, const char *src) { assert( dest ); assert( src ); char *save = dest; while(*dest++ = *src++); return save; } //同等效率也可以这么写 char *strcpy(char *dest, const char *src) { char *save = dest; for (;;) { *dest = *src; if (*src == '/0') break; ++dest, ++src; } return save; } [8] strstr /* 返回第一个匹配的子字符串。例如: src: abcd efghcd abcdef dst:cd return: cd efghcd abcdef */ #include <cstdio> #include <cstring>// strlen #include <cassert>// assert #include <conio.h>// getch //#include <string>//strstr char* strstr(char* src,char* dst) { assert(src); assert(dst); //calculate the each size char *szSrc=src,*szDst=dst; int nSrcSize=strlen(szSrc),nDstSize=strlen(szDst); //check if (nSrcSize<nDstSize) { return NULL;//wrong } //compare int nCompareTime=nSrcSize-nDstSize+1; int j1,j2; for (j1=j2=0; j1<nSrcSize && j2<nDstSize; ++j1) { if (src[j1]!=dst[j2]) { if (j1>nCompareTime-1) { return NULL;//No substring } j2=0; continue; } else//to find the first same value { ++j2; } } if (j2==nDstSize)//absolute equal { return &src[j1-nDstSize];//have substring } return NULL;//No substring } int main() { //char *szSrc = "wcdj is a guy", *szDst = "is"; char szSrc[128]={0},szDst[128]={0}; printf("input src: "); //scanf("%s",szSrc); gets(szSrc); printf("input dst: "); //scanf("%s",szDst); gets(szDst); char* ptr=strstr(szSrc,szDst); if (ptr) { printf("The substring is: %s/n", ptr); } else { printf("has no substring/n"); } getch(); return 0; } [9] String Class #include <iostream> #include <cstring> using namespace std; class String { public: String(const char *str=NULL); // 普通构造函数 String(const String &other); // 拷贝构造函数 ~String(); // 析构函数 String& operator = (const String &other); // 赋值函数 char *GetString(){ return this->m_data; } private: char *m_data;// 用于保存字符串 }; String::String(const char *str/* =NULL */) { // strlen在参数为NULL时会抛出异常,所以需要此步判断 if (str==NULL) { m_data=new char[1]; m_data[0]='/0'; } else { m_data=new char[strlen(str)+1]; strcpy(m_data,str); } } String::String(const String &other) { m_data=new char[strlen(other.m_data)+1]; strcpy(m_data,other.m_data); } String& String::operator = (const String &other) { if (this==&other) { return *this; } else { delete []m_data; m_data=new char[strlen(other.m_data)+1]; strcpy(m_data,other.m_data); return *this; } } String::~String() { delete []m_data; } int main() { String str1;// 普通构造函数 cout<<str1.GetString()<<"[end]"<<endl; char szStr[]="wcdj"; String str2(szStr);// 普通构造函数 cout<<str2.GetString()<<"[end]"<<endl; String str3(str2);// 拷贝构造函数 cout<<str3.GetString()<<"[end]"<<endl; String str4=str3;// 拷贝构造函数(why) str4=str3;// 赋值函数 cout<<str4.GetString()<<"[end]"<<endl; return 0; } [10] 写一个函数找出一个整数数组中,第二大的数 (microsoft) const int MINNUMBER = -32767 ; int find_sec_max( int data[] , int count) { int maxnumber = data[0] ; int sec_max = MINNUMBER ; for ( int i = 1 ; i < count ; i++) { if ( data[i] > maxnumber ) { sec_max = maxnumber ; maxnumber = data[i] ; } else { if ( data[i] > sec_max ) sec_max = data[i] ; } } return sec_max ; } 

 

 

 

你可能感兴趣的:(String,tree,null,delete,BT,DST)