2.3数据结构
数组和字符串:用连续的内存存储数字和字符。
链表和树:因操作时会用到大量的指针,解决问题时留意代码的鲁棒性。
栈:一个与递归紧密相关的数据结构。
队列:与广度优先遍历紧密相关
数组
时间复杂度为O(1),空间效率不高。
使用动态数组时,尽量减少改变容量大小的次数,减少时间上的消耗。
PS:C/C++中没有记录数组的大小,用指针访问时留意边界条件。
再用sizeof()求值时,数组名只有在单独出现的时候才代表整个数组,其他时候都表示为首元素或首元素的地址。
//二维数组中查找(从左到右从上到下增大)
//思路:选取右上角数进行比较,相等退出;如果右上角的数大于Key值则剔除该列;反之剔除该行
bool Find(int *matrix, int rows, int cols, int key)
{
bool find = false;
if (matrix != NULL && rows > 0 && cols > 0)
{
int row = 0;
int col = cols - 1;
while (row < rows && col >= 0)//row[),col[]
{
if (matrix[row*cols + col] == key)
{
find = true;
break;
}
else if (matrix[row*cols + col] > key)
{
col--;
}
else
{
row++;
}
}
}
return find;
}
字符串
字符串是由若干个字符组成的序列。
C/C++中每个字符串的结尾都是以‘\0’作为结尾。
为节省内存,C/C++把常量字符串放到单独的一个内存区域。当几个指针赋值给相同的常量字符串时,它们实际上指向相同的内存地址。常量字符串赋值给不同的数组时情况于此不同。
void _tmain()
{
char str1[] = "hello world";
char str2[] = "hello world";
char* str3 = "hello world";
char* str4 = "hello world";
if (str1 == str2)
printf("str1==str2");
else
printf("str1!=str2"); //会被打印
if (str3 == str4)
printf("str3==str4"); //会被打印
else
printf("str3!=str4");
}
//空格替换为%20
//思路:反向由字符串尾开始遍历替换
//举一反三:A1,A2数组有序,A1内存足够将A2插入A1尾部并有序
//合并两个数组是发都可考虑右后向前移动
//时间复杂度为O(n)
void ReplaceBlank(char string[], int length)//length是为字符串开辟的数组空间长度int
{
if (string != NULL || length <= 0)
{
return;
}
int OldLength = 0;//字符串原长度
int NumBlank = 0;//记录空格数
int i = 0;
while (string[i] != '\0')
{
OldLength++;
if (string[i] == ' ')
{
NumBlank++;
}
++i;
}
int NewLength = OldLength + NumBlank * 2;//空格替换后的字符长度
if (NewLength > length)//判断字符空间是否足够
return;
int OldIndex = OldLength;
int NewIndex = NewLength;//新字符串末尾的下标
while (OldIndex >= 0 && NewIndex > OldIndex)//判断新字符串是否增长
{
if (string[OldIndex] == ' ')
{
string[NewLength] = '0';
string[NewLength] = '2';
string[NewLength] = '%';
}
else
{
string[NewLength--] = string[OldLength];
}
OldLength--;
}
}
链表
链表是一种动态数据结构,因此创建时不需要知道链表的长度。当插入一个新节点时为节点分配内存,然后调整链表指针的指向。内存分配不是在创建链表时一次性完成,而是每次添加一个节点分配一次内存。因此链表的空间的效率比数组高。
//链表尾插
struct ListNode
{
int data;
ListNode* next;
};
void PushBack(ListNode** pHead, int value)//因为有可能改变头结点,所以用二级指针串头结点
{
ListNode* pNew = new ListNode();
pNew->data = value;
pNew->next = NULL;
if (*pHead == NULL)
{
*pHead = pNew;
}
else
{
ListNode* pNode = *pHead;
while (pNode->next != NULL)
{
pNode = pNode->next;
}
pNode->next = pNew;
}
}
void RemoveNode(ListNode** pHead, int value)
{
if (pHead == NULL&&*pHead == NULL)
{
return;
}
ListNode* del = NULL;
if ((*pHead)->data == value)
{
del = *pHead;
*pHead = (*pHead)->next;
}
else
{
ListNode* pNode = *pHead;
while (pNode->next != NULL && pNode->next->data != value)
{
pNode = pNode->next;
}
if (pNode->next != NULL&&pNode->next->data == value)//判断是遍历完链表还是找到目标节点
{
del = pNode->next;
pNode->next = pNode->next->next;
}
}
if (del != NULL)
{
delete del;
del = NULL;
}
}
//从尾到头打印链表
//思路:链表由尾到头打印的顺序类似于栈的后进先出,考虑用栈解决
void RePrintList(ListNode* pHead)
{
stack nodes;
ListNode* pNode = pHead;
while (pNode != NULL)
{
nodes.push(pNode);
pNode = pNode->next;
}
while (!nodes.empty())
{
pNode = nodes.top();
cout << pNode->data << " ";
nodes.pop();
}
}
void RePrintListR(ListNode* pHead)//递归可以看做是一个栈结构,因此可用递归解决
{
if (pHead != NULL)
{
if (pHead->next != NULL)//递归存在的问题在于如果链表过长,栈开辟空间是可能会发生栈溢出
{
RePrintListR(pHead->next);
}
cout << pHead->data << " ";
}
cout << endl;
}
树
二叉树是树的一种特殊的数据结构。
二叉树的特例:二叉搜索树,堆和红黑数
最大堆中根节点的值最大。
最小堆中根节点的值最小。
红黑树的最长路径不超过最短路径的两倍。
STL中set,multiset,map,multimp基于红黑树实现。
//重建二叉树
//根据前序遍历和后序遍历建立二叉树
//思路:将建立二叉树分为建立左,右子树的问题,发现两者本质上一样,问题简化为建立子树,可用递归完成
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* Construct(int* pre, int* inor, int length)
{
if (pre == NULL || inor == NULL || length <= 0)
return NULL;
return ConstructCore(pre, pre + length - 1, inor, inor + length - 1);
}
BinaryTreeNode* ConstructCore(int* startPre, int* endPre, int* startInor, int* endInor)
{
//前序遍历的第一个数是根节点值
int rootValue = startPre[0];
BinaryTreeNode* root = new BinaryTreeNode();
root->m_nValue = rootValue;
root->m_pLeft = root->m_pRight = NULL;
if (startPre == endPre)
{
if (startInor == endInor&&*startPre == *startInor)
return root;
else
throw std::exception("Invalid input.");
}
//在中序遍历中找到根节点值
int* rootInor = startInor;
while (rootInor <= endInor&&*rootInor != rootValue)
++rootInor;
if (rootInor == endInor&&*rootInor != rootValue)
throw std::exception("Invalid input.");
int leftLength = rootInor - startInor;
int* leftPreorderEnd = startPre + leftLength;
if (leftLength > 0)
{
//构建左子树
root->m_pLeft = ConstructCore(startPre + 1, leftPreorderEnd, startInor, rootInor - 1);
}
if (leftLength < endPre - startPre)
{
//构建右子树
root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPre, rootInor + 1, endInor);
}
return root;
}
前序遍历序列的第一个数字便是根节点值,由此创建根节点,接下来在中序遍历序列中找到根节点的位置,这样就能确定左、右子树的节点数量。在前序遍历和后序遍历中划分了左右子树,以此重新建立二叉树。
栈和队列
实际应用中,操作系统会给每个线程创建一个栈用来存储函数调用各个函数的参数、返回地址及临时变量。
栈通常是一个不考虑排序的数据结构,需要O(n)时间找到栈中最大或最小的元素。
队列:先进先出,与广度优先遍历紧密联系,如二叉树的层序遍历。
//栈和队列
//利用两个栈构建一个队列(利用两个队列实现一个栈)
template
class CQueue
{
public:
CQueue(void);
~CQueue(void);
void appendTail(const T& node);//
T deleteHead();
private:
stack stack1;
stack stack2;
};
template
void CQueue::appendTail(const T& element)
{
stack1.push(element);
}
template
T CQueue::deleteHead()
{
if (stack2.size() <= 0)
{
while (stack1.size() > 0)
{
T& data = stack1.top();
stack1.pop();
stack2.push(data);
}
}
if (stack2.size() == 0)
throw new exception("queue is empty");
T head = stack2.top();
stack2.pop();
return head;
}