三、编程题
1.比较字符串大小,如果字符串1大于字符串2,返回1,相等返回0,小于则返回-1;
1. int strcmp(const char* str1, const char* str2)
2. {
3. int ret = 0;
4. while(!(ret=*(unsigned char*)str1-*(unsigned char*)str2) && *str1)
5. {
6. str1++;
7. str2++
8. }
9.
10.
11. if (ret < 0)
12. {
13. return -1;
14. }
15. else if (ret > 0)
16. {
17. return 1;
18. }
19. return 0;
20. }
2.单链表反置。
1. struct ListNode
2. {
3. int m_nKey;
4. ListNode* m_pNext;
5. };
6.
7. #include "stdafx.h"
8. #include
9. #include
10.
11. using namespace std;
12.
13. struct ListNode
14. {
15. int m_nKey;
16. ListNode* m_pNext;
17. };
18.
19. //构造链表
20. void CreateList(ListNode *&pHead)
21. {
22. fstream fin("list.txt");
23. ListNode *pNode = NULL;
24. ListNode *pTmp = NULL;
25. int data;
26. fin>>data;
27. while (data)
28. {
29. pNode = new ListNode;
30. pNode->m_nKey = data;
31. pNode->m_pNext = NULL;
32. if (NULL == pHead)
33. {
34. pHead = pNode;
35. pTmp = pNode;
36. }
37. else
38. {
39. pTmp->m_pNext = pNode;
40. pTmp = pNode;
41. }
42.
43. fin>>data;
44. }
45. }
46.
47. //翻转单链表
48. void ReverseLink(ListNode *&pHead)
49. {
50. if (NULL == pHead)
51. {
52. return;
53. }
54. ListNode *pNode = pHead;
55. ListNode *Prev = NULL;
56. ListNode *pNext = NULL;
57. while (NULL != pNode)
58. {
59. pNext = pNode->m_pNext;
60. if (NULL == pNext)
61. {
62. pHead = pNode;
63. }
64. pNode->m_pNext = Prev;
65. Prev = pNode;
66. pNode = pNext;
67. }
68. }
69.
70. void PrintList(ListNode *pHead)
71. {
72. if (NULL == pHead)
73. {
74. return;
75. }
76. ListNode *pNode = pHead;
77. while (NULL != pNode)
78. {
79. cout<
80. pNode = pNode->m_pNext;
81. }
82. cout<
83. }
84.
85. int _tmain(int argc, _TCHAR* argv[])
86. {
87. ListNode *pHead = NULL;
88. cout<<"原来的链表:";
89. CreateList(pHead);
90. PrintList(pHead);
91. ReverseLink(pHead);
92. cout<<"翻转的链表:";
93. PrintList(pHead);
94.
95. return 0;
96. }
3.实现atoi函数
1. #include "stdio.h"
2. #include "ctype.h"
3. #include "stdlib.h"
4.
5. /*
6. Converts a character string into an int or long
7. 将一个字符串转化为整数
8. */
9. int my_atoi(char s[])
10. {
11. int i,n,sign;
12.
13. for(i=0;isspace(s[i]);i++); //跳过空白
14.
15. sign=(s[i]=='-')?-1:1;
16. if(s[i]=='+'||s[i]==' -') //跳过符号位
17. i++;
18. for(n=0;isdigit(s[i]);i++)
19. n=10*n+(s[i]-'0'); //将数字字符转换成整形数字