数据结构学习01总结
指针
int *p1=&A;
这儿的*是为了说明定义的是指针类型
P1=&D;
这句的意思是P1指向D的地址
E=*p1;
是说明要取p1所指变量的值
折半查找
-
/* * 折半查找 (递归算法) 成功返回要查找数的index 不成功返回-1 */ int midfind(int s[], int x, int left, int right) { if (left <= right){ if (x < s[(left + right) / 2]) { midfind(s, x, left, (left + right) / 2 - 1); } else if (x > s[(left + right) / 2]) { midfind(s, x, (left + right) / 2 + 1, right); } else { return (left + right) / 2; } } else { return -1; } }
-
/*折半查找 非递归算法 */ int midfind2( int s[], int x, int length) { int left = 0; int right = length - 1; while (left <= right) { if (x < s[(left + right) / 2]) { right = (left + right) / 2 - 1; } else if (x > s[(left + right) / 2]) { left = (left + right) / 2 + 1; } else { return (left + right) / 2; } } return -1; }
知识点
循环队列计算队列元素个数的公式(n+r-f)%n
注:非循环队头-队尾r-f即可,循环有可能为负数则加上总个数n再对n取余。
数据结构算法设计
有序链表的合并
void MergeList(LinkList &a LinkList &b LinkList &c)
{
pa=La->next;
pb=Lb->next;
Lc=pc=La;
while(pa&&pb)
{
if(pa->date<pb->date)
{
pc->next=pa; pc=pa; pa=pa->next; } else if(pa->date>pb->date) { pc->next=pb; pc=pb; pb=pb->next; } else { pc->next=pa; pc=pa; pa=pa->next; q=pc->next; delete pb; pb=q; } } pc->next=pa?pa:pb; delete Lb;
}
树的总结点数、叶子结点数
#include <stdio.h>` #include <stdlib.h>` `typedef struct _BT_NODE` `{` `int data;` `struct _BT_NODE* left;` `struct _BT_NODE* right;` `}BT_NODE;` `BT_NODE* AppendNode(int data)` `{` `BT_NODE* node=(BT_NODE*)malloc(sizeof(BT_NODE));` `node->left=NULL;` `node->right=NULL;` `node->data=data;` `return node;` `}` `int BinTreeNodeCount(BT_NODE* root)` `{` `int nodeNum=1;` `if(!root)return 0;` `nodeNum+=BinTreeNodeCount(root->left);` `nodeNum+=BinTreeNodeCount(root->right);` `return nodeNum;` `}` `int BinTreeLeafNodeCount(BT_NODE* root)` `{` `int nodeNum=0;` `if(!root)return 0;` `if(root->left==NULL && root->left==NULL)` `nodeNum++;` `else` `{` `nodeNum+=BinTreeLeafNodeCount(root->left);` `nodeNum+=BinTreeLeafNodeCount(root->right);` `}` `return nodeNum;` `}` `int main(void) {` `BT_NODE* root;` `/*` `` 10 /\ 20 30 `15 16` `*/` `root=AppendNode(10);` `root->left=AppendNode(20);` `root->right=AppendNode(30);` `root->left->left=AppendNode(15);` `root->left->right=AppendNode(16);` `` printf("The binary tree has %d node(s).\n",BinTreeNodeCount(root)); printf("The binary tree has %d leaf node(s).\n",BinTreeLeafNodeCount(root)); return 0; `}`