C描述資料結構
阿新 • • 發佈:2021-01-30
C描述資料結構
1.指標的定義使用以及取地址符&使用
#include <stdio.h>
int main(int argc, char const *argv[])
{
int *point = 0;
int num = 10;
point = #
printf("*point value = %d.\n",*point);
return 0;
}
result:
*point value = 10.
2.函式定義呼叫以及引數指標傳遞實際值修改
#include <stdio.h>
int max(int x, int y);
void swap_two_nums(int *xp, int *yp);
int main(int argc, char const *argv[])
{
int *point1 = 0;
int *point2 = 0;
int num1 = 10;
int num2 = 11;
printf("num1 value = %d.\n", num1);
printf("num2 value = %d.\n", num2);
point1 = &num1;
point2 = &num2;
swap_two_nums(point1, point2);
printf("After swap:===========================\n");
printf("num1 value = %d.\n", num1);
printf("num2 value = %d.\n", num2);
printf("Max value = %d.\n", max(num1, num2));
return 0;
}
int max(int x, int y)
{
return x > y ? x : y;
}
void swap_two_nums(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
result:
num1 value = 10.
num2 value = 11.
After swap:===========================
num1 value = 11.
num2 value = 10.
Max value = 11.
3. 結構體呼叫,typedef 使用
#include <stdio.h>
// struct Node
// {
// int value;
// struct Node *Next;
// };
typedef struct Node
{
int value;
Node *Next;
} Node;
int main(int argc, char const *argv[])
{
Node n1, n2, n3;
Node *np1, *np2, *np3;
np1 = &n1;
np2 = &n2;
np3 = &n3;
n1.value = 1;
n1.Next = np2;
n2.value = 2;
n2.Next = np3;
n3.value = 3;
n3.Next = 0;
return 0;
}
result:
4. 遞迴呼叫以及動態規劃解決斐波那契數列第n項值
#include <stdio.h>
int feibo(int n);
int main(int argc, char const *argv[])
{
int sum = feibo(5);
return 0;
}
// int feibo(int n){ // 遞迴
// if(n<=1) return 1;
// return feibo(n-1) + feibo(n-2);
// }
int feibo(int n)
{
int array[10] = {0};
array[0] = array[1] = 1;
while (--n) // 陣列滾動,[n & 1],一直讓陣列下標 在 0和1之間重複
{
array[n & 1] = array[0] + array[1];
printf("%d.\n", n & 1);
}
return array[1];
}
result:
0.
1.
0.
1.
The fifth num is :8.
使用動態規劃可以減少使用的空間,只需要將重複的子問題的解存放在一個數組中即可。