Linked Lists
Linked Lists
Linked Lists
Problem: Given a linked list and a key `X`, check if `X` is present in the linked list or not.
Solution:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
int X1 = 14;
int X2 = 13;
Problem: Insert a node at the given position in a linked list. We are given a pointer to a node,
and the new node is inserted after the given node.
Solution:
class LinkedListInsertion {
// Function to insert a new node after a given node
public static void insertAfter(Node prevNode, int newData) {
// Check if the previous node is null
if (prevNode == null) {
System.out.println("The given previous node cannot be null.");
return;
}
Problem: Given the head of a sorted linked list, delete all duplicates such that each element
appears only once. Return the linked list sorted as well.
Solution:
class LinkedListRemoveDuplicates {
// Function to remove duplicates from a sorted linked list
public static Node removeDuplicates(Node head) {
Node current = head;
// Remove duplicates
head = removeDuplicates(head);
Problem: Given the head of a singly linked list, return `true` if it is a palindrome or `false`
otherwise.
Solution:
import java.util.Stack;
class LinkedListPalindrome {
// Function to check if a linked list is a palindrome
public static boolean isPalindrome(Node head) {
Stack<Integer> stack = new Stack<>();
Node current = head;
Q4. Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// Step 3: Compare the first half with the reversed second half
Node firstHalf = head;
while (secondHalf != null) {
if (firstHalf.data != secondHalf.data) {
return false;
}
firstHalf = firstHalf.next;
secondHalf = secondHalf.next;
}
return true;
}
Q5. Given two numbers represented by two lists, write a function that returns the sum list. The
sum list is a list representation of the addition of two input numbers.
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// If there is still a carry left, add a new node with the carry
if (carry > 0) {
current.next = new Node(carry);
}
return dummyHead.next;
}