diff --git a/LinkedList/Cpp/detect-cycle-in-linked-list.cpp b/LinkedList/Cpp/detect-cycle-in-linked-list.cpp new file mode 100644 index 0000000..df7c2ea --- /dev/null +++ b/LinkedList/Cpp/detect-cycle-in-linked-list.cpp @@ -0,0 +1,23 @@ +/** + * 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) { + ListNode *slow = head; + ListNode *fast = head; + if(head == NULL) return false; + while(fast != NULL && fast->next != NULL){ + fast = fast->next->next; + slow = slow->next; + if(slow == fast) return true; + } + return false; + + } +}; diff --git a/LinkedList/Cpp/flatten-binary-tree-to-linked-list.cpp b/LinkedList/Cpp/flatten-binary-tree-to-linked-list.cpp new file mode 100644 index 0000000..91a646d --- /dev/null +++ b/LinkedList/Cpp/flatten-binary-tree-to-linked-list.cpp @@ -0,0 +1,27 @@ +/** + * Definition for a binary tree node. + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode() : val(0), left(nullptr), right(nullptr) {} + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} + * }; + */ +class Solution { +private: + TreeNode* prev = NULL; +public: + void flatten(TreeNode* root) { + if(!root) return; + + flatten(root->right); + flatten(root->left); + + root->right = prev; + root->left = NULL; + prev = root; + + } +}; diff --git a/LinkedList/Cpp/merge-two-sorted-linked-lists.cpp b/LinkedList/Cpp/merge-two-sorted-linked-lists.cpp new file mode 100644 index 0000000..bf101b5 --- /dev/null +++ b/LinkedList/Cpp/merge-two-sorted-linked-lists.cpp @@ -0,0 +1,34 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + if(head == NULL) return NULL; + if(head -> next == NULL and n == 1) return NULL; + ListNode * temp = head; + int count = 1; + while(temp -> next != NULL){ + temp = temp -> next; + count++; + } + if(count == n) return head -> next; + ListNode * ans = head; + int count2 = count; + while(ans -> next != NULL){ + if(count2 == n+1){ + ans -> next = ans -> next -> next; + break; + } + else {ans = ans -> next; count2--;} + } + return head; + } +};