reverse a linked list in matlab

To reverse a linked list in Matlab, you can follow these steps:

  1. Initialize three variables, "prev", "curr" and "next".
  2. Assign "prev" to null, "curr" to the head of the linked list, and "next" to null.
  3. Traverse the linked list till "curr" is not null.
  4. Inside loop, assign "next" to "curr.next".
  5. Now, set "curr.next" as "prev".
  6. Move "prev" to "curr" and "curr" to "next".
  7. Finally, set the head of the linked list to "prev".

Here's the code implementation in Matlab:

main.m
function head = reverseLinkedList(head)
    prev = null;
    curr = head;
    next = null;

    while(curr ~= null)
        next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    end
    head = prev;
end
239 chars
14 lines

This function takes the head of the linked list as the input argument, and returns the reversed linked list. You can call this function by passing the head of the linked list as shown below:

main.m
head = reverseLinkedList(head);
32 chars
2 lines

gistlibby LogSnag