- 因为在复习数据结构和C语言,试卷上的算法题只可以使用纯C去完成, 所以这里为了以防万一,复习一下二重指针。
需求: 将某个变量传参之后, 需要改变这个变量的地址, 将本变量指向一个新的地址。
typedef struct SqStack
{
int data[maxSize];
int top;
}SqStack;
void changePoint(SqStack **fir) // 因为传入的是 地址的地址, 所以可以改变fir的地址。
{
SqStack sec;
sec.top = 999;
*fir = &sec;// 将sec的地址 传给fir。实现地址改变。
}
int main()
{
SqStack *fir;
fir = (SqStack *)malloc(sizeof(SqStack));
fir->top=-1;
printf("fir的地址为:%d fir的top值为%d
",fir,fir->top);
changePoint(&fir); // 取出fir地址的地址,作为参数传入。
printf("fir的地址为:%d fir的top值为%d
",fir,fir->top);
return 0;
}
- 运行结果如下:
fir的地址为:10490928 fir的top值为-1
fir的地址为:6421568 fir的top值为999
Process returned 0 (0x0) execution time : 0.016 s
Press any key to continue.
额外再加一个代码补充一下吧。
/* 单链表/链栈 节点的定义 */
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
void initStact(LNode **L)
{
*L = (LNode *)malloc(sizeof(LNode));
(*L)->data=443; //考虑到运算符优先级的问题,这里需要加括号。
}
int main()
{
LNode *lnode;
printf("变量地址:%d
",lnode);
initStact(&lnode);
printf("变量地址 %d data值:%d
",lnode,lnode->data);
return 0;
}
- 运行结果
变量地址:16
变量地址 7279664 data值:443
Process returned 0 (0x0) execution time : 0.000 s
Press any key to continue.
- 补充
/* 二重指针的补充
Q: 一个栈, 当其栈满时,将其maxSize扩充至二倍。
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct SqStack
{
int *data;
int top;
int maxSize;
}SqStack;
void initSqStact(SqStack **sq,int maxSize)
{
*sq = (SqStack *)malloc(sizeof(SqStack));
(*sq)->data = (int *)malloc(maxSize*sizeof(int));
(*sq)->maxSize=maxSize;
(*sq)->top=-1;
}
int push(SqStack *sq,int x)
{
if(sq->top==sq->maxSize-1){
if(!stackFull(sq)){
return 0; //因为栈满 所以去申请新的空间,如果申请失败则将失败抛出。
}// 如果申请成功则继续执行。
}
sq->data[++sq->top]=x;
return 1; // 添加成功。
}
int stackFull(SqStack *sq)
{
int *temp = (int *)malloc(2*sq->maxSize*sizeof(int));
if(temp==NULL)
return 0; //空间申请失败。
int i;
for(i=0;i<sq->maxSize;i++)
temp[i] = sq->data[i]; // 将原来的元素赋予现在开辟的空间。
free(sq->data);
sq->data = temp;
return 1;
}
int main()
{
SqStack *sq;
initSqStact(&sq,4);
push(sq,2);
push(sq,3);
push(sq,4);
push(sq,5);
push(sq,6);
for(int i=0;i<=sq->top;i++){
printf("%d
",sq->data[i]);
}
}
二叉排序树(用到了一点二重指针 略微有点麻烦, 然后记录一下。)
typedef struct BTNode
{
int key;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode;
BTNode* BSTSearch(BTNode *bt,int key)
{
if(bt==NULL)
return NULL;
else
{
if(bt->key==key)
return bt;
else if(bt->key<key)
return BSTSearch(bt->lchild,key);
else
return BSTSearch(bt->rchild,key);
}
}
int BSTInsert(BTNode **bt,int key)
{
if((*bt)==NULL)
{
(*bt)=(BTNode *)malloc(sizeof(BTNode));
(*bt)->lchild=(*bt)->rchild=NULL;
(*bt)->key=key;
return 1;
}
else
{
if((*bt)->key==key)
return 0;
else if((*bt)->key<key)
return BSTInsert(&((*bt)->lchild),key);
else
return BSTInsert(&((*bt)->rchild),key);
}
}
void CreateBST(BTNode **bt,int *key,int n)
{
int i;
(*bt)=NULL;
for(int i=0;i<n;i++)
{
BSTInsert(bt,key[i]);
}
}
int main()
{
BTNode *bt;
int key[]={1,2,3,4,5,6,7,8,9,0};
CreateBST(&bt,key,10);
printf("%d",bt->lchild->lchild->lchild->key);
}