Reputation: 43
I'm having a bit of an issue with implementing my circularly linked list. I'm working on a problem that requires you to implement any ADT yourself. I seem to be okay with adding nodes to the list, however I'm in unfamiliar territory when it comes to removing. I included the first two remove methods to give you an idea of where my head is at, how would I go about removing the last node in the list?
public class LinkedList {
private Node head;
private Node tail;
private int size = 0;
LinkedList() {
head = null;
current = null;
previous = null;
tail = null;
size = 0;
}
//checks if list is empty
public boolean isEmpty() {
return head == null;
}
//add new node to front of circularly linked list
public void addToFront(E x) {
if (head == null) {
head = new Node(x);
} else {
Node n = new Node(x);
x.next() = head;
head = x;
}
}
public void addtoMiddle(E x) {
x.next = current.next();
current.next = x;
size = size + 1;
}
public void addToEnd(E x) {
x.next = null;
tail.next() = x;
tail = x;
size = size + 1;
}
public void removeFirst(E x) {
if (head = null) {
System.out.println("Error! List is empty!");
} else {
head = current.next();
size = size + 1;
}
}
public void removeMiddle(E x) {
previous.next() = current.next();
current.next() = null;
size = size + 1;
}
Upvotes: 4
Views: 1387
Reputation: 332
I know this is not directly an answer to your question but I feel like Thomas has given the needed explanation here.
Since you have a lot of syntax or incompleteness errors in the example I would recommend to comment out all functions so it has no more errors. Then comment them in again one by one correcting every error.
Some advices:
You use class members which are not defined e.g. current
, previous
.
Decide if next
should be a member or function.
You need to define a class for Node
(containing its members and functions), like you did for LinkedList
.
Upvotes: 0
Reputation: 88757
In a circular linked list the last node's next
points to the head, so you loop through your nodes until node.next.equals( head )
. Note that next
must never be null and if you have only one node then you have head.next = head
.
In a circular doubly linked list you also have a previous
node, i.e. you can iterate backwards. In that case your last node is just head.previous
.
A small ascii picture:
head -next---> node -next---> node -next---> last
| ^ <---prev- <---prev- <---prev- | ^
| | | |
| |_____________________________________next_| |
|_prev_________________________________________|
Upvotes: 3