javafunctiondoubly-linked-listdequesentinel

How can I get the index of a specific node in a doubly linked list?


I have a class called SLList whuch accepts a doubly linked list SLList of any generic type as an input.

I've decided to use a sentinel approach to aid in my task.

I am now trying to convert my doubly linked list into a string using function public String makestring() and also get the index of a specific node via function public T findindexof(int i)

Here is my code so far:

public class SLList<T>{ 
        private class IntNode {
        private T data;
        private IntNode previous;
        private IntNode next;

        public IntNode (T data, IntNode previous, IntNode next) {
            this.data = data;
            this.previous = previous;
            this.next = next;
        }

        public IntNode () { 
            next = previous = this;
        }
    }

    IntNode sentinel; 
    private int length = 0;

    public SLList(){
        sentinel = new IntNode(); // Self referencing previous/next
    }

    
    public String makestring() {
        return sentinel.data.toString();
    }
    public T findindexof(int i) {
        return sentinel.data[i];
    }

My findindexof(int i) must only get the item at the given index, where 0 is the front, 1 is the next item and so forth. If no such item exists, returns null. It must not alter the deque either.

I am struggling to understand how to implement this function, so any advice would be greatly appreciated.

Thank you


Solution

  • You can loop for i iterations, moving between nodes through the next field each time.

    public T findindexof(int i) {
        IntNode curr = sentinel;
        for (int j = 0; j < i && curr != null; j++)
            curr = curr.next;
        return curr != null ? curr.data : null;
    }