0

I'm trying to add a node in a circular list in Java. The problem is that my list has only a head (without a tail). Here is my code:

import java.io.PrintStream;
import java.util.EmptyStackException;

public class CircularList {
    private Node head = null;

    private class Node {
        public Node(String payload, Node prev, Node next) {
            super();
            this.payload = payload;
            this.prev = prev;
            this.next = next;
        }

        private Node prev;
        private Node next;
        String payload = "";
    }
    public void push(String payload) {
        Node n = new Node(payload, null, null);
        if (isEmpty()) {
            head = n;
            n.next = n;
        } else {
            n.prev = head;
            n.next = head;
        }
    }
1
  • From the sounds of it, you want to add a new object and have it be the new head of the list? Is that what you mean by push? Commented Aug 9, 2022 at 13:44

2 Answers 2

1

Lets take some nodes.

< H - < A - < B -

This describes the connections of the nodes. A.next == H and A.prev == B.

H and B are special cases, where H is the head and B is the tail. Since the list is circular. Then H.next == B and B.prev == H.

When we push a node.

< N - < H - < A - < B -

Then we can see all of the assignments that need to change.

H = head;
B = H.next; // get the tail since you only have the head.
H.next = N;
N.prev = H;
N.next = B;
B.prev = N;
head = N;
Sign up to request clarification or add additional context in comments.

Comments

0

You're almost there. When the list is empty, that part works fine. But when the list is not empty, think through what needs to happen, which is 4 things:

  • The 'head's previous node needs to become the new node.
  • The new node's 'next' needs to point at head.
  • The new node's 'previous' needs to point at what used to be head.prev.
  • What used to be head.prev's next pointer needs to point at the new node.

You'll need some temp variables to take care of all of that.

2 Comments

Should the new node become the head? It seems like you've written this such that the new node becmes the second node.
OP's question is unclear. I would assume that head remains unchanged, and that the new node can be gotten to either by traversing forward (.next.next.next.next....) until you get there, or by going back 1 step (head.prev points at the new node). That should mirror the notion of 'add at the end'. If OP wants the added node to be head, you still need to update 4 things, just update them slightly differently. This answer is meant to guide them there (primarily, clue in that 4 things need updating and that temp variables may be required).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.