mparrish91 mparrish91 - 2 months ago 12
Objective-C Question

Pass by Pointer Objective C - Linked List

I am working on this problem to return the Kth to Last element of a singly linked list

I am trying to implement this C solution which passes the value by reference. and do so in Objective C passing by pointer

Currently the code runs infinitely and I am not sure if it is possible in Objective C passing by pointer

C++ Example Code First

C example code

My example in Objective C

enter image description here

Answer

Just out of curiosity, why are you trying to do this in Obj-C? You can compile using C++. I am asking because you don't seem to have a grasp of pass by reference versus pointers. Additionally if you did want to do this in Obj-C, you can still do pass by reference.

In any case you have a few problems with your code:

  • Since you've changed to using a pointer, you need to pass the address of i.
  • Since you are now using a pointer, you have to dereference, increment, and reassign your increment
  • You did not copy the example code properly and used head instead of head->next

Full code below. I did not compile or double check if it truly runs. Based on visual inspection of your code and the example you provided.

- (Node *)nthToLast:(int)k withHead:(Node *)head andCounter:(int *)i {
    // If Node is an Obj-C class, then use nil
    // If Node is a C++ struct/class then use NULL
    // If you have c++11 and it is a C++ struct/class use nullptr
    if (head == nil) {
        return nil;
    }

    Node *nd = [self nthToLast:k withHead:head->next andCounter:i];

    // I've pulled the value in count to make it clear what is being done
    // i++ is pointer arithmetic, which is not what you want to do here
    int count = *i;

    ++count;

    *i = count;

    if (count == k) {
        return head;
    }

    return nd;
}

- (Node *)nthToLast:(int)k withHead:(Node *)head {
    int i=0;
    return [self nthToLast:k withHead:head andCounter:&i];
}
Comments