0
/**
 * 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:
    bool ans = false;
    bool isPalindrome(ListNode* head) {
        ListNode* f = head;
        helper(f, head);
        ...
        return somthing....

    }
    
    void helper(ListNode* f, ListNode* b) {
        if (!b->next)
            return f->val == b->val;
        
        int f_test = f->val;
        int b_test = b->val;
        bool ret = helper(f, b->next);
        int f_test1 = f->val;
        int b_test1 = b->val;
        cout<<f_test <<": "<< f_test1<<endl;
        
        f = f->next;
            
        
    }
};

This helper function is used to check if a LinkedList is Palindrome. so I want to use two pointers one point to the end and another pointing to the beginning. and check the values. to simplify my issue I removed the logic after f = f->next;

Actually, my question is why the f is not changed since I have f = f->next. so the f_test and f_test1 should be different.

if the input is [1,2,,3, 4] in my understanding, the print list should be:

1: 2

2: 3

3: 4

but actually, it's not like that this.

is someone could help me with this?

BigTree
  • 23
  • 1
  • 4
  • 1
    you have a short circuit return with bool expression in `helper`but it doesn't return bool. It should not compile. And if it will, it would be Undefined Behavior(UB) because it doesn't return value unless short circuit is fired. – Swift - Friday Pie May 16 '22 at 22:34
  • 2
    `f` is an input parameter, its scope is limited to the function call, assigning new value to `f` at the end of function is pointless, this indeed has no effect. Also, your `helper` function is declared to return `void`, I think it should return `bool`, at least according the current implementation, and should return something at the end. –  May 16 '22 at 22:38
  • 1
    If you want to check if it's a palindrome, then why use a forward (single link) list? _"why the `f` is not changed since I have `f = f->next`"_ - because, as @Sedenion mentioned, `f` is local to `helper`. If you want to change it, you need to take the pointer by reference: `void helper(ListNode*& f, ListNode* b)` ... and also since `helper` doesn't return anything ( `void`), then what do you expect `return helper(f, head);` to return? – Ted Lyngmo May 16 '22 at 22:59
  • Thanks for the quick response. after using reference it solves my issue. – BigTree May 16 '22 at 23:39
  • Does this answer your question? [Function does not change passed pointer C++](https://stackoverflow.com/questions/11842416/function-does-not-change-passed-pointer-c) – trincot May 17 '22 at 19:33

0 Answers0