Java single LinkedList add with O(1) complexity - java

I'm trying to understand LinkedLists(Single LinkedList to be precise).
I heard/read that delete and add operation will be performed with O(1) complexity and I'm still not getting how to implement with O(1) complexity for these two operation.
Below is my implementation in java(NOTE: I don't know c, c++ coding, So I recently started understanding data structures).
public class Node
{
private Integer data = null;
private Node next = null;
private int size = 0;
public Node()
{
}
private Node(Integer data)
{
this.data = data;
}
public boolean add(Integer data)
{
if (null == data) return false;
if (null == this.data)
{
this.data = data;
}
else
{
if (null == this.next)
{
this.next = new Node(data);
}
else
{
this.next.add(data);
}
}
size += 1;
return true;
}
public Integer getDataAt(int index)
{
if (index == 0)
{
return this.data;
}
else
{
return this.next.getDataAt(index - 1);
}
}
public int getSize()
{
return size;
}
}
Please suggest me to edit as of now add(data) to make it O(1) complexity.

Only Adding and Removing operation in LinkedList is O(1) but traversing to the node you want to remove or add is an O(N) operation
You can achieve the O(1) complexity if you keep the reference to your last added element so you can put add new Node to the last traversed element's next Node.

In linkedList if you have head and tail pointer to point first and last of node linkedlist then in constant time you can add and remove in first or last position of the node.If you want to delete an element you have to find that element and in worst case that element will be in last .In doubly linkedlist you can start from start and end so you have to traverse till so in worst case it will be O(n).

Thank you for all your support, as a NOOB in data structure I want to understand how ds workds rather than copy pasting from someone's else implementation.
Neeraj Jain & Gati Sahu's explanations/answer helped me to achieve what I'm looking for add(data) in LinkedList with O(1) complexity.
So what I did is "Segregate Plain Node class and create LinkedList class with operations.
class Node
{
private Integer data = null;
private Node next = null;
public Node(Integer data)
{
super();
this.data = data;
}
public Integer getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setData(Integer data)
{
this.data = data;
}
public void setNext(Node next)
{
this.next = next;
}
}
public class LinkedList
{
Node head;
Node end;
public Node getHead()
{
return head;
}
public boolean add(Integer data)
{
if (null == head)
{
head = new Node(data);
end = head;
}
else
{
addAtEnd(data);
}
return true;
}
public void addAtEnd(Integer data)
{
end.setNext(new Node(data));
end = end.getNext();
}
public void addAtFirst(Integer data)
{
Node tmpNode = head;
head = new Node(data);
head.setNext(tmpNode);
}
}

Related

How to remove from a Linked list in Java?

So I wrote my own linked list (and list node) in Java as a part of a homework.
Now, I'm trying to erase entries, but the function is not working.
I know the concept:
Search for node keeping the previous;
Tell previous node to point to next node;
Return or stop using the node so GC erases it.
For some reason it is not working. I can delete the node with the same value over and over. I'm afraid it is something related to Java pointers.
The code:
Node:
public class SimpleNode<E> {
private E value;
private SimpleNode<E> next;
public SimpleNode() {
this.value = null;
this.next = null;
}
public NoSimples(E data, SimpleNode<E> ref) {
this.value = data;
this.next = ref;
}
// Getters and Setters
}
List:
public class LinkedList<E> implements Iterable<SimpleNode<E>> {
private SimpleNode<E> head;
private int size = 0;
public LinkedList() {
this.head = new SimpleNode<E>();
}
public void add(SimpleNode<E> node) {
this.addFirst(node.getValue());
}
public void addFirst(E item) {
SimpleNode<E> nonde = new SimpleNode<E>(item, this.head);
this.head = node;
size++;
}
public void add(E value) {
this.addFirst(value);
}
public SimpleNode<E> removeFirst() {
SimpleNode<E> node = this.head;
if (node == null) {
return null;
} else {
this.head = node.getNext();
node.setNext(null);
this.size--;
return node;
}
}
public SimpleNodes<E> remove(E value) {
SimpleNode<E> nodeAnt = this.head;
SimpleNode<E> node = this.head.getNext();
while (node != null) {
if (node.getValue()!= null && node.getValue().equals(value)) {
nodeAnt.setNext(node.getNext());
node.setNext(null);
return node;
}
nodeAnt = node;
node = node.getNext();
}
return null;
}
// Other irrelevant methods.
}
Multiple Problems :
Think if you have a list 1,2,3,4. Now, if you try to remove 1, your code fails.
nodeAnt = node should be nodeAnt = nodeAnt.getNext(). Remember, the're all references, not Objects
Also, a recursive way might be easier to understand. For example, Here is how I implemented it
public void remove(E e){
prev = head;
removeElement(e, head);
System.gc();
}
private void removeElement(E e, Node currentElement) {
if(currentElement==null){
return;
}
if(head.getData().equals(e)){
head = head.getNext();
size--;
}else if(currentElement.getData().equals(e)){
prev.setNext(currentElement.getNext());
size--;
}
prev = prev.getNext();
removeElement(e, currentElement.getNext());
}
Note: I delete all occurrences of the Element, as I needed it. You may need it to be different.

Delete Item - Doubly Linked list using Tail Recursion

I am currently learning Doubly Linked Lists.
I have managed to convert write a doubly linked list that was nearly 100% functional. However I need to learn how to write it with tail recursion.
Below is my DLLNode code:
public class DLLNode
{
private DLLNode previous;
public DLLNode next;
private String value;
public DLLNode(String value)
{
this.value = value;
this.previous = previous;
this.next = next;
}
public DLLNode(String value, DLLNode next, DLLNode previous)
{
this.value = value;
this.next = next;
this.previous = previous;
}
public String GetDataItem()
{
return value;
}
public void setDataItem()
{
this.value = value;
}
public DLLNode GetPreviousNode()
{
return previous;
}
public void setPrevious(DLLNode previous)
{
this.previous = previous;
}
public DLLNode GetNextNode()
{
return next;
}
public void setNextNode(DLLNode next)
{
this.next = next;
}
public void addItem(String value) {
if(this.next == null) {
// Stopping condition
DLLNode newNode = new DLLNode(value);
this.next = newNode;
} else {
// Recurse
this.next.addItem(value);
}
}
}
I have managed to get my AddItem working using tail recursion and I'm now looking into getting delete Item working. I'm guessing that like addItem I need deleteItem adding to my DLLNode.
Below is my DoublyLinkedList class:
public class DoublyLinkedList
{
private int noOfItems;
private DLLNode head;
private DLLNode tail;
// Default constructor
public DoublyLinkedList()
{
head = null;
tail = null;
this.noOfItems = 0;
}
public void DeleteItem(int index)
{
if (index ==0)
{
System.out.println("Out of Bounds");
}
if (index > noOfItems)
{
System.out.println("Out of Bounds");
}
if (head == null)
{
System.out.println("No Item to remove");
}
else if (index == 1)
{
head = head.GetNextNode();
noOfItems--;
}
else
{
int position = 0;
DLLNode currentNode = head;
while (currentNode != null) {
if (position == index-1) {
currentNode.setNextNode(
currentNode.GetNextNode().GetNextNode());
noOfItems--;
break;
}
currentNode = currentNode.GetNextNode();
position++;
}
}
}
}
Any tips on where I can get started with converting this code would be greatly appreciated.
Kind Regards,
Ben.
P.S. Apologies for the way the code has formatted - I've tried to fix it but it won't seem to sort. Can anyone good at formatting code on her please try and sort it out?
private void DeleteItemHelper(final int indexToDelete, int curIndex, DLLNode curNode) {
if (curIndex == indexToDelete) {
// Handle removing a node with both a previous and next nodes.
}
else {
DeleteItemHelper(indexToDelete, curIndex + 1, curNode.getNextNode());
}
}
public void DeleteItem(int index) {
DeleteItemHelper(index, 0, head);
}
Without further testing I think that you are forgetting to re-set the head reference of the node following the removed node:
if (position == index-1) {
// Tail of currentNode is set to the node following
// next node, but head of that node still points to the
// node which should be removed from list
currentNode.setNextNode(
currentNode.GetNextNode().GetNextNode());
noOfItems--;
break;
}

convert below singly Linked list to doubly linked list

I already wrote a small program of single linked list with add and traverse method in that. Now I want to convert it into a doubly linked list. I know all the concept of doubly linked list but I am facing little difficulty to implement it in my program.
public class SingleLinkList<T> {
private Node<T> head;
private Node<T> tail;
public void add(T element)
{
Node<T> nd = new Node<T>();
nd.setValue(element);
if (head==null)
{
head = nd;
tail = nd;
}
else
{
tail.setNextRef(nd);
tail = nd;
}
}
public void traverse(){
Node<T> tmp = head;
while(true){
if(tmp == null){
break;
}
System.out.println(tmp.getValue());
tmp = tmp.getNextRef();
}
}
public static void main (String args[])
{
SingleLinkList<Integer> s1 = new SingleLinkList<Integer>();
s1.add(2);
s1.add(3);
s1.add(3);
s1.traverse();
}
}
class Node<T> {
private T value;
private Node<T> nextRef;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public Node<T> getNextRef() {
return nextRef;
}
public void setNextRef(Node<T> nextRef) {
this.nextRef = nextRef;
}
public int compareTo(T arg)
{
if (arg==this.value)
{
return 0;}
else
{return 1;}
}
}
Add a Node<T> prevRef field to your list class with appropriate getters and setters and then add this method:
public void linkReverse(Node<T> head) {
if (head == null) {
return;
}
head.setPrevRef(null);
if (head.getNextRef() == null) {
return;
}
Node<T> prev = head;
Node<T> curr = head.getNextRef();
while (curr != null) {
curr.setPrevRef(prev);
prev = curr;
curr = curr.getNextRef();
}
}
This method will walk down a currently singly linked list and will link each node in reverse, leaving the list doubly linked.
Of course, you would need to modify the other methods as well, but this is at least a good starting point.
just add private Node<T> prevRef; instance variable to Node class, and set it during add() method. I suggest that traverse() will receive a boolean (or even better, enum) direction argument

Understanding doubly linked circular list

I have an assignment in my CS class about circular doubly linked lists. We are given a Node class that sets up the links and such.
public class Node {
private Node previous, next;
private Object data;
public Node(Object data) {
this.data = data;
}
public Node() {
}
public Node(Object data, Node previous, Node next) {
this.previous = previous;
this.next = next;
this.data = data;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
and we are tasked with implementing a few methods. In the list class there is one Node created called 'base'
public class DList {
private Node base;
public DList() {
}
all of the methods require some form of traversing the list. From what I understand setting up a temp node to be equal to base.getNext() will give me the first node of the list and testing if temp != base will be my check for reaching the end of the list since the base node serves as an anchor for the rest of the nodes (if my understanding is correct).
However, when I try to do bits of code such as:
public int size() {
int count = 0;
if (base.getNext() == base)
return count;
else {
Node temp = base.getNext();
while (temp != base) {
temp = temp.getNext();
count++;
}
}
return count;
}
I get a null pointer exception at the line where I say Node temp = base.getNext(); and for the life of me I cannot understand why, because like I said earlier I thought that base.getNext() would be the first element of my list.
There is no need for a dummy base node. In that case base initially is null.
In that case:
public int size() {
int count = 0;
if (base != null) {
Node temp = base;
do {
temp = temp.getNext();
count++;
} while (temp != base);
}
return count;
}

Linked List Wrong Output Java

Hey ya'll I am having a little trouble with my singly linked list. I decided to create a simple one because we do not get enough practice during my data structures class and cannot seem to find why I am not getting the right output.
The code is:
package linked_list;
public class LinkedList {
private Node head;
private Node tail; // After figuring out head, come back to this FIXME
private int listSize;
public LinkedList() {
head = new Node(null);
tail = new Node(null);
}
public void addLast(String s) {
Node newNode = new Node(s);
if (head == null) {
addFirst(s);
} else {
while (head.next != null) {
head = head.next;
}
head.next = newNode;
tail = newNode;
}
listSize++;
}
public void addFirst(String s) {
Node newNode = new Node(s);
if (head == null) {
head = newNode;
tail = newNode;
}
else {
newNode.next = head;
head = newNode;
}
listSize++;
}
public Object getFirst() {
return head.data;
}
public Object getLast() {
return tail.data;
}
public void clear() {
head = null;
tail = null;
listSize = 0;
}
public Object peek() {
try {
if (head == null) {
throw new Exception ("The value is null");
}
else {
return head;
}
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public int size() {
return listSize;
}
// This class has the ability to create the nodes that are used
// in the Linked List.
private class Node {
Node next;
Object data;
public Node(String value) {
next = null;
data = value;
}
public Node(Object value, Node nextValue) {
next = nextValue;
data = value;
}
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
Now here is my driver that I created to run a simple little operation:
package linked_list;
public class LinkedListDriver {
public static void main(String[] args) {
LinkedList list1 = new LinkedList();
list1.clear();
list1.addLast("This goes last");
list1.addFirst("This goes first");
list1.addLast("Now this one goes last");
System.out.println(list1.getFirst());
System.out.println(list1.getLast());
}
}
My output is this:
This goes last
Now this one goes last
I guess my question is why am I not getting the answer This goes first from my getFirst() method. It seems to be something wrong with the order or structure of that method but I cannot pinpoint it.
When you are in the else in the addLast, you are changing the reference to head. You should use another reference pointer to traverse the list when adding in the else.
Also, your list size should only be incremented in the else in addLast because you are incrementing twice otherwise (once in addFirst and again after the if-else in addLast).

Categories

Resources