LeetCode 141.环形链表
**知识点:**判断链表是否有环,快慢指针分别只移动一个节点和两个节点,当两指针重合,表示有环。环形链表没有节点指向null。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL){
return false;
}
ListNode *lowPtr = head, *fastPtr = head;
while(fastPtr->next != NULL && fastPtr->next->next != NULL){
**//如果这里的判断写成lowPtr->next != NULL && fastPtr->next->next != NULL会报错**
lowPtr = lowPtr->next;
fastPtr = fastPtr->next->next;
if(lowPtr ==fastPtr){
return true;
}
}
return false;//环形链表没有节点指向null。
}
};
LeetCode 297.序列化与反序列化二叉树
因为string 只能从尾部弹出字符pop_back,不能从头部弹出,所以我用queue作为辅助,保存序列化的结果。但是提交结果显示内存超出限制。改成list则不会超出限制。不懂
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
string rserialize(TreeNode* root,string& str){
if(root == nullptr){
str += "None,";
return str;
}
str += to_string(root->val)+",";
rserialize(root->left,str);
rserialize(root->right,str);
return str;
}
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string str = "";
return rserialize(root,str);
}
TreeNode* deserialize(queue<string>& dataArray) {
if(dataArray.front() == "None"){
dataArray.pop();
return nullptr;
}
TreeNode *head = new TreeNode(stoi(dataArray.front()));
dataArray.pop();
head->left = deserialize(dataArray);
head->right = deserialize(dataArray);
return head;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
queue<string> dataArray;
string str;
for(auto &c : data){
if(c == ','){
dataArray.push(str);
str.clear();
}else{
str += c;
}
}
return deserialize(dataArray);
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));