开宗明义:本系列基于牛客网剑指offer,刷题小白,一天两道我快乐!旨在理解和交流,重在记录,望各位大牛指点!
牛客网-剑指offer
1、复杂链表的复制
描述:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)。
思路:
- 在旧链表中创建新结点,比如
A
A
A 创建
A
1
A1
A1;
- 将
A
1
A1
A1 连接到
A
A
A 后面;
- 然后从旧链表中拆分得到新链表;
测试代码:
#include <vector>
#include <stdio.h>
struct RandomListNode {
int label;
RandomListNode *next, *random;
RandomListNode(int x) :label(x), next(NULL), random(NULL) {
//
}
};
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if (!pHead)
return NULL;
nodeClone(pHead); //第一步,克隆
connectRandom(pHead); //第二步,连接
return reconnect(pHead); //第三步,分割
}
//[1]复制结点,插入到原结点后方
void nodeClone(RandomListNode *head)
{
RandomListNode *pNode = head;
while (pNode != NULL)
{
RandomListNode *pClone = new RandomListNode(pNode->label); //这边新建一个节点
pClone->next = pNode->next; //这边把A1连接到A后面
pNode->next = pClone;
pNode = pClone->next;
}
}
//[2]还原新结点的random指针,因为有两个指针,上面往下,这个是random
void connectRandom(RandomListNode *head)
{
RandomListNode *pNode = head;
while (pNode != NULL)
{
RandomListNode *pClone = pNode->next;
if (pNode->random)
{
pClone->random = pNode->random->next;
}
pNode = pClone->next;
}
}
//[3]拆分
RandomListNode *reconnect(RandomListNode *head)
{
RandomListNode *pNode = head;
RandomListNode *result = head->next;
while (pNode != NULL)
{
pNode->next = pNode->next->next;
pNode = pNode->next;
//
if (pNode != NULL)
pNode->next->next = pNode->next;
//
}
return result;
}
};
2、二叉搜索树与双向链表
描述:输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
首先介绍一下:什么是双向链表?
双向链表中,每个结点也有两个指针,它们分别指向前一个结点和后一个结点。
思路:中序遍历的非递归算法,修改当前遍历节点与前一遍历节点的指针指向。
二叉搜索树的中序遍历为一个排序好的队列。那么本题就变成了将二叉搜索树进行中序遍历,并转换成双向表。
分为三步:
- 找到最底层的左叶子节点,并作为双向链表的头节点;
- 对于不是头节点的点,调整链表的指针:当前节点的左节点作为上一个节点;上一个节点的右节点指向当前节点;
- 跳转到当前节点的右节点;
测试代码:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {
}
};
//
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(pRootOfTree == nullptr)
return nullptr;
TreeNode* pre = nullptr;
convertHelper(pRootOfTree, pre);
TreeNode* res = pRootOfTree;
//
while(res ->left)
res = res ->left;
return res;
}
void convertHelper(TreeNode* cur, TreeNode*& pre)
{
if(cur == nullptr)
return;
convertHelper(cur ->left, pre);
cur ->left = pre;
if(pre)
pre ->right = cur;
pre = cur;
convertHelper(cur ->right, pre);
}
};