Similar Problems
Similar Problems not available
How to recursively print a linked list ? - Leetcode Solution
Companies:
LeetCode: How to recursively print a linked list ? Leetcode Solution
Difficulty: Unknown
Topics: linked-list
How to recursively print a linked list ?
Linked List is a linear data structure in which each node points to the next node in the linked list.
Linked List is also a recursive data structure, for example we can say that each node of a linked list points to another linked list as shown in the diagrams below:
Linked list thought of normally
We can also think of the above linked list as this:
Linked List thought recursively
When we think of the linked list as recursive data structure, as shown in the diagram above. We can say that Node 1 points to another linked list (B) of size 2, similarly node 2 points to a linked list of size 1, node 3 points to a linked list of size 0
This observation will help us print the linked list recursively
Therefore, to print this linked list recursively , we will write a function which prints the current node first and then prints the remaining Linked List (B) recursively.
How to recursively print a linked list ? Solution Code
1class Solution {
2public:
3 bool checkInclusion(string s1, string s2) {
4 int len1 = s1.length(), len2 = s2.length();
5 if (len1 > len2) return false;
6
7 vector<int> count(26, 0); // Using vector instead of array
8 for (int i = 0; i < len1; i++) {
9 count[s1[i] - 'a']++;
10 count[s2[i] - 'a']--;
11 }
12 if (allZero(count)) return true;
13
14 for (int i = len1; i < len2; i++) {
15 count[s2[i] - 'a']--;
16 count[s2[i - len1] - 'a']++;
17 if (allZero(count)) return true;
18 }
19
20 return false;
21 }
22
23private:
24 bool allZero(const vector<int>& count) {
25 for (int i = 0; i < 26; i++) {
26 if (count[i] != 0) return false;
27 }
28 return true;
29 }
30};
31