Custom Linked List Example In Java

Sanjay Singh
2 min readAug 25, 2020

--

package com.simple.datastructure;

public class CustomLinkedListExample {

private static class Node {
private int data;
private Node next;

public Node(int data) {
this.data = data;

}
}

/* Method no 1 */
/* display all linked list element */
public void displayElement(Node head) {
if (head == null) {
return;
}
Node current = head;
while (current != null) {
System.out.print(current.data + “” + “ — — →”);
current = current.next;
}
System.out.print(current);
}

/* Method no 2 */

/* Find out the length of linkedlist */

public int findLength(Node head) {
int count = 0;
if (head == null) {
return 0;
}
Node current = head;
while (current != null) {
count++;

current = current.next;

}
return count;

}

/* Method no 3 */

/* insert node at beginning */

public Node insertNodeAtStarting(Node head, int data) {

Node node = new Node(data);

if (head == null) {
return node;
}
// add new node as head
node.next = head;

return head = node;

}

/* Method no 4 */

/* insert node at End */

public Node addNodeAtEnd(Node head, int data) {
Node endElement = new Node(data);
if (head == null) {
return endElement;
}
Node current = head;
while (null != current.next) {
current = current.next;
}
current.next = endElement;
return head;
}

/*
* Method no 5 Ques -How to insert node in LL after a given node
*/

public void insertNodeAfterGivenNode(Node node, int data) {

if (node == null) {

}
Node newElement = new Node(data);
newElement.next = node.next;
node.next=newElement;

}
/*
* Method no 5 Ques -How to insert node at given possion
*
*
*/

public void insertNodeAtGivenPossion(int possion ,int data) {

if(possion==)

}

public static void main(String[] args) {
CustomLinkedListExample custom = new CustomLinkedListExample();
/* add value into node */
Node head = new Node(10);
Node second = new Node(40);
Node third = new Node(90);
Node fourth = new Node(60);

/* linked node with other node */
head.next = second;
second.next = third;
third.next = fourth;
fourth.next = null;

custom.displayElement(head);

int length = custom.findLength(head);
System.out.println(“ “ + length);

/* insert node at beginning */
//Node newHead = custom.insertNodeAtStarting(head, 50);
//custom.displayElement(newHead);
//System.out.println();
/* insert node at end */
//Node endNode = custom.addNodeAtEnd(newHead, 900);
//custom.displayElement(endNode);
/* method no 5 */

custom.insertNodeAfterGivenNode(head, 30);
custom.displayElement(head);

}

}

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet