DEV Community

subash
subash

Posted on Edited on

What is Nodes in linkedlist

A Node is a small container that stores data and the address of the next node.

types of linked list

Type Connection
Singly Next
Doubly Previous and Next
Circular Last connects to First

What is HEAD?

HEAD is a pointer that stores the address of the first node.

class Node {
    int data;
    Node next;

    Node(int value) {
        data = value;
        next = null;
    }
}

public class Main {
    public static void main(String[] args) {

        Node first = new Node(10);
        Node second = new Node(20);
        Node third = new Node(30);

        first.next = second;
        second.next = third;

        Node head = first;
    }
}
Enter fullscreen mode Exit fullscreen mode

HOW TO PRINT A LINKED LIST?

suppose we want to print all elements.

Node temp = head;

while (temp != null) {
    System.out.println(temp.data);
    temp = temp.next;
}
Enter fullscreen mode Exit fullscreen mode

output:
10
20
30

Insertion in Linked List

insertion at the begginning

before insertion

HEAD
|
↓
[10] → [20] → [30] → NULL

Node newNode = new Node(5); \\create an object containing 5

newNode.next = head; \\Connects the new node to the existing first node.

head = newNode;\\Updates HEAD to point to the new first node.
Enter fullscreen mode Exit fullscreen mode

HEAD
|
↓
[5] → [10] → [20] → [30] → NULL

insertion at the end;

HEAD
|
↓
[10] → [20] → [30] → NULL

Node newNode = new Node(40);  \\Creates a new node containing 40.

Node temp = head;   \\ Starts from the first node.

while (temp.next != null) {
    temp = temp.next;
}

//after the while loop temp.next have null value so the while loop stop 

temp.next = newNode;
\\ after this line newNode will replace the null , after that temp.next is 40 that have null indefault 
(class Node {
    int data;
    Node next;)

}
Enter fullscreen mode Exit fullscreen mode

1. Delete the First Node

head = head.next;
Enter fullscreen mode Exit fullscreen mode

2. Delete the Last Node

Node temp = head;

while (temp.next.next != null) {
    temp = temp.next;
}

temp.next = null;

Enter fullscreen mode Exit fullscreen mode


Node first = new Node(10);
Node head = first;

Node newNode = new Node(5);

newNode.next = head;
head = newNode;
Enter fullscreen mode Exit fullscreen mode

What will happen?

A) Both first and head point to 5.

B) first points to 10, and head points to 5.

C) Both first and head point to 10.

Think carefully! 😊

Top comments (0)