1. 赋值运算符函数(或应说复制拷贝函数问题)
1
2
3
4
5
6
7
8 |
class
A { private : int
value; public : A( int
n) : value(n) {} A(A O) { value = O.value; } // Compile Error : (const A& O) }; |
因为,A a(0); A b = a; 就会使程序陷入死循环。
2. 实现 Singleton 模式 (C#)
3.二维数组中的查找
Sample:
二维数组:Matrix[4][4],行列都是递增。
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
判断 value = 7 是否在数组。
思路:从右上角开始,若大于 7 删去一行; 若小于 7 删去一列。
代码:
1 #include<iostream> 2 const int N = 4; 3 int data[][N] = {{1, 2, 8, 9},{ 2, 4, 9, 12},{4, 7, 10, 13}, {6, 8, 11, 15}}; 4 5 bool find(int (*matrix)[N], int row, int column, int value) 6 { 7 int r = 0, c = column - 1; 8 while(r < row && c >= 0) 9 { 10 if(matrix[r][c] == value) return true; 11 else 12 { 13 if(matrix[r][c] > value) --c; 14 if(matrix[r][c] < value) ++r; 15 } 16 } 17 return false; 18 } 19 20 int main() 21 { 22 std::cout << find(data, 4, 4, 10) << std::endl; 23 return 0; 24 }
4.替换空格 时间:O(n) 空间:O(1)
Sample:
输入: S:"We are happy."
输出:S:"We%20are%20happy."
1 #include<stdio.h> 2 #include<string.h> 3 const int N = 18; 4 /* length is the full capacity of the string, max number of elements is length-1*/ 5 void ReplaceBank(char s[], int length){ 6 if(s == NULL && length <= 0) return; // program robustness 7 int nowLength = -1, numberOfBlank = 0; 8 while(s[++nowLength] != ‘\0‘){ 9 if(s[nowLength] == ‘ ‘) ++numberOfBlank; 10 } 11 int newLength = nowLength + numberOfBlank * 2; // newLength is the number of elements 12 if(newLength >= length) return; 13 14 int idOfNow = nowLength, idOfNew = newLength; // both point to ‘/0‘ 15 while(idOfNow >= 0){ /* key program */ 16 if(s[idOfNow] == ‘ ‘) { 17 strncpy(s+idOfNew-2, "%20", 3); 18 idOfNew -= 3; 19 --idOfNow; 20 }else 21 s[idOfNew--] = s[idOfNow--]; 22 } 23 } 24 25 int main(){ 26 char s[N] = "We are happy."; 27 puts(s); 28 ReplaceBank(s,N); 29 puts(s); 30 return 0; 31 }
5.从尾到头打印链表
1. 询问是否可以改变链表结构,若可以,则空间O(1);否则,
2. 使用栈,或者递归。
a. 使用栈:
1 #include <iostream> 2 #include <string> 3 #include <stack> 4 5 struct LinkNode{ 6 char e; 7 LinkNode *next; 8 }; 9 10 void print(LinkNode *Head) 11 { 12 std::stack<char> st; 13 while(Head != NULL) 14 { 15 st.push(Head->e); 16 Head = Head->next; 17 } 18 while(!st.empty()) 19 { 20 printf("%c ", st.top()); 21 st.pop(); 22 } 23 printf("\n"); 24 } 25 26 LinkNode* init(const std::string &s) 27 { 28 size_t i = 0; 29 LinkNode *head, *p; 30 p = head = NULL; 31 while(i < s.length()) 32 { 33 LinkNode *p2 = new LinkNode; 34 p2->e = s[i++]; p2->next = NULL; 35 if(head == NULL) 36 head = p = p2; 37 else 38 { 39 p->next = p2; 40 p = p->next; 41 } 42 } 43 return head; 44 } 45 int main() 46 { 47 const std::string s = "ABCDEFG"; 48 LinkNode *Head = init(s); 49 print(Head); 50 return 0; 51 }
b. 使用递归:
1
2
3
4
5
6 |
void
RecursivePrint(LinkNode *Head) { if (Head == NULL) return ; RecursivePrint(Head->next); printf ( "%c " , Head->e); } |
6.
Chap2: question: 1 - 10,布布扣,bubuko.com
原文:http://www.cnblogs.com/liyangguang1988/p/3667443.html