data structures - How to check the symmetry of an integer singly-linked list in C++? -
I have a question about a single-linked list in C ++.
An integer array is called [0 .. n] symmetric if array [0] = array [n], array [1] = array [n -1], ...
For example: 1 2 3 4 5 4 3 2 1
So, is there a way to check the symmetry of an integer single-linked list?
I have thought of copying their value under an array, then check the symmetry this array but I think it is not good because the hidden things in the links list will be lost.
The way in the classic fold and press the elements halfway on a stack, then from the stack Pop and compare the remaining elements.
bool isPalindrome (forward_list & lt; int & gt; & amp; l) {forward_list & lt; Integer & gt; Pile; Auto = l.begin (); Int len = 0; Int i = 0; While (this! = L.end ()) {++ len; This ++; } If (lane and lieutenant; = 1) are true; This = l.begin (); While (i & lt; (lane / 2)) {stack.push_front (* it); ++ i; This ++; } If ((lane% 2) == 1) ++; While (! Stack.empty ()) {if (stack.front (!)! = * It) false return; Stack.pop_front (); This ++; } Back true; } Bool test_good (const int i) {int j = i / 2; Forward_list & lt; Integer & gt; L; For (int k = 0; k & lt; j; k ++) {l.push_front (k); } If (i% 2 == 1) {l.push_front (j); } For (int k = j-1; k> = 0; k -) {l.push_front (k); } Refunded iPandrom (L); } Bool test_bad (const int i) {forward_list & lt; Int & gt; L; For (int k = 0; k & lt; i; k ++) {l.push_front (k); } L.push_front (i); L.push_front (i + 1); Come back! IPalmel (L); } Int main () {for (int i = 0; i & lt; 20; i ++) {cout & lt; & Lt; "Exam for" & lt; & Lt; I & lt; & Lt; "..."; If (test_good (i)) cout & lt; & Lt; "Fine..."; And I come back; If (test_bad (i)) cout & lt; & Lt; "Fine." & Lt; & Lt; Endl; And I come back; } Return 0; }
I used forward_list
to apply a stack instead of using a dedicated std :: stack
template. Besides, note that the problem is complex when using the generic lists of T
, because you do not want to instantize the values in the list, while pressing the stack, Can not push primitive types (such as char
or int
) for that problem, you have to provide two different templated implementations, according to T
according to enable_if
ed. You might also add a comparison operator to the template.
Comments
Post a Comment