简单的题目4
来源:互联网 发布:金融网络销售靠谱吗 编辑:程序博客网 时间:2024/04/30 15:22
#include <iostream>using namespace std;/* 反向打印链表,其实就是个递归,没啥稀奇的 还有将堆栈内容存储 反向打印字符串 顺序打印一个大整数的各个数字 都用递归 */struct Node{ int value; Node *next;}; Node* createLinkedList(int *,int);void printBackward(Node*,Node*);void clearLinkedList(Node *);int main(){ int a[8]; int b[10]; for(int i=0;i<sizeof(a)/sizeof(int);i++) a[i] = 2*i; for(int i=0;i<sizeof(b)/sizeof(int);i++) b[i] = 2*i+1; Node *head = createLinkedList(a,8); printBackward(head,head); clearLinkedList(head); cin.get(); }Node* createLinkedList(int *a,int n){ Node *head = new Node; Node *p = head; for(int i=0;i<n;i++) { Node* q = new Node; q->value = a[i]; q->next = 0; p->next = q; p = q; } return head; }void clearLinkedList(Node *head){ while(head) { Node *p = head; head = head->next; delete p; }}void printBackward(Node* node,Node* head){ if(!node) return; printBackward(node->next,head); if(node!=head) //建链表的时候多了个头,头不打印 cout<<node->value<<" "; }
/* 两种写operator=的方式 */class CMyString{public: CMyString(char* pData=0); CMyString(const CMyString& str); ~CMyString(void); CMyString& operator=(const CMyString& str);private: char* m_pData; };//教科书版的 CMyString& CMyString::operator=(const CMyString& str){ if(this==&str) return *this; delete[] m_pData; //网上很多这个程序直接malloc(sizeof(str)) //很明显错的 m_pData = new char[strlen(str.m_pData)+1]; strcpy(m_pData,str.m_pData); return *this; }//利用拷贝构造函数 //好处是原始对象不会因为new出错而变化 CMyString& CMyString::operator=(const CMyString& str){ if(this!=&str) { CMyString tempString(str); char* temp = tempString.m_pData; tempString.m_pData = m_pData; m_pData = temp; } return *this; }
/* 对于连续的数组常用的处理方法: 一个索引迭代遍历寻找特定的元素 两个索引一头一尾,比如翻转字符串 两个索引都从头开始,比如一个索引当作插入位置,另一个索引遍历删除数组中某个集合的所有元素 不用索引,采用hash hash也有两种方式,一种hash地方是连续的,然后遍历hash的地方 另一种是离散的hash,这里用这个*//* 一个数组中只有2个数字是只有一个,其他都有两个 求这两个数 */ #include <iostream>using namespace std;void seekChars(char*);int main(){ char* a = "qwertyuiop45qwertyuiop"; seekChars(a); cin.get(); }void seekChars(char* str){ int table[128] = {0}; //hashTable写起来太麻烦 //思路就是第一个出现则塞入hashTable //出现过删除,最后剩下的字符就是要求的字符 for(char* p=str;*p!='\0';p++) { if(table[*p]==0) table[*p] = 1; else table[*p] = 0; } for(int i=0;i<128;i++) { if(table[i]) cout<<char(i)<<" "; } }
#include <iostream>using namespace std;/* 在一个字符串中找到第一个只出现一次的字符: 遍历两遍,第一遍hash,第二遍找到hash里面为1的第一个字符 */char firstChar(char*);int main(){ char* str = "asdfwdfverag43afd23sce"; cout<<firstChar(str); cin.get(); }char firstChar(char* str){ char table[128]; for(char* p=str;*p!='\0';p++) table[*p]++; for(char *p=str;*p!='\0';p++) if(table[*p]==1) return *p; }