0% found this document useful (0 votes)
3 views4 pages

Linked List Operations in Java

Uploaded by

sarahloner030
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Linked List Operations in Java

Uploaded by

sarahloner030
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Palindrome

class Solution {

public boolean isPalindrome(ListNode head) {

if (head == null || [Link] == null) return true;

ListNode slow = head, fast = head;

// Find the middle (slow will be at middle)

while (fast != null && [Link] != null) {

slow = [Link];

fast = [Link];

// For odd number of nodes, move slow one more step

if (fast != null) {

slow = [Link];

// Reverse second half

slow = reverseList(slow);

// Compare both halves

fast = head;

while (slow != null) {

if ([Link] != [Link]) {

return false;

slow = [Link];

fast = [Link];
}

return true;

private ListNode reverseList(ListNode head) {

ListNode previous = null;

ListNode current = head;

while (current != null) {

ListNode next = [Link]; // save next

[Link] = previous; // reverse pointer

previous = current; // move previous

current = next; // move current

return previous; // new head

Remove linked list elements:

class Solution {

public ListNode removeElements(ListNode head, int val) {

ListNode temp = new ListNode(0) , curr = temp;

[Link] = head;

while([Link] != null ){

if([Link] == val) [Link] = [Link];

else curr = [Link];

}
return [Link];

Delete the Middle Node of a Linked List

class Solution {

public ListNode deleteMiddle(ListNode head) {

if ([Link] == null) return null;

ListNode slow = head, fast = [Link];

while (fast != null && [Link] != null) {

slow = [Link];

fast = [Link];

[Link] = [Link];

return head;

Remove Nth Node From End of List

class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {

ListNode dummy = new ListNode(0, head); // Create a dummy node


before head

ListNode fast = dummy;

ListNode slow = dummy;

// Move fast pointer n steps ahead

for (int i = 0; i < n; i++) {

fast = [Link];

// Move both fast and slow until fast reaches the end

while ([Link] != null) {

fast = [Link];

slow = [Link];

// Skip the target node

[Link] = [Link];

return [Link];

You might also like