1

I have a class SLList where a doubly linked list SLList would be taking in values of any generic type.

I have used sentinels to help myself in working with these, and 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;

    public SLList() {
        sentinel = new IntNode();
    }

    public int size() {
        int x = 0;
        while (sentinel.next != null) {
            x++;
        }
        return x;
    }

    public String makestring() {
        return sentinel.data.toString();
    }
}

Now I'm trying to turn my doubly linked list into a string using makestring() but I'm confused on how can I implement this properly into code. Can anyone please explain what am I doing wrong?

Also, if anyone can see if my size() function is wrong, please feel free to correct me

Abra
  • 19,142
  • 7
  • 29
  • 41
Nutnicha
  • 335
  • 1
  • 10
  • When you create your SLList it already has one element. What do you do with this existing element when you add another element? You have to indicate the method that adds the element. –  Oct 05 '22 at 06:05
  • so while(sentinel.next != null) { x++; } return x; ? – Nutnicha Oct 05 '22 at 06:07
  • since SLList already have one element – Nutnicha Oct 05 '22 at 06:08
  • [Edit] your question and post a [mcve]. Create a [doubly-linked] list and then post what string should be returned by method `makestring` for this list. – Abra Oct 05 '22 at 06:10
  • Would be more efficient if you keep track of the size each time the list is modified. – Cheng Thao Oct 05 '22 at 06:10
  • @ChengThao can u elaborate please. I don't know how to do this with sentinels present. – Nutnicha Oct 05 '22 at 06:19
  • 3
    The title is "find the size of the list" the question body is "how to implement makestring?". Please pick one question and stick with it – knittl Oct 05 '22 at 07:10
  • What Cheng Thao means is that you shouldn't calculate the size in `size()` but keep a variable in your list and each time you add a node you increment and each time you remove a node you decrement that variable. – Thomas Oct 05 '22 at 07:38
  • As for "how to implement `makestring()`?" - think about what exactly you'd like the string to contain. What's its purpose? If you can provide that information you might already see some implementation options as well. And please don't ask "what should I put into the string?" - that's _your_ decision. – Thomas Oct 05 '22 at 07:40

0 Answers0