Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
Approach
Java
public class RemoveLinkedListElements {public static void main(String[] args) {ListNode l = new ListNode(1);l.next = new ListNode(2);l.next.next = new ListNode(6);l.next.next.next = new ListNode(3);l.next.next.next.next = new ListNode(4);l.next.next.next.next.next = new ListNode(5);l.next.next.next.next.next.next = new ListNode(6);int val = 6;ListNode node = removeElement(l, val);System.out.println("After Removing :");linkedListTraversal(node);}private static void linkedListTraversal(ListNode node) {while (node != null) {System.out.print(node.val + " ");node = node.next;}}public static ListNode removeElement(ListNode head, int n) {// If list is nullif (head == null) {return head;}ListNode root = head;// if deleted element in beginningwhile (root != null) {// if found then deleteif (root.val == n) {root = root.next;} else {break;}}ListNode prev = root;ListNode prev1 = root;while (prev != null) {// if found nth then deletewhile (prev != null && prev.val == n) {prev1.next = prev.next;prev = prev.next;}// change previousprev1 = prev;if (prev != null)prev = prev.next;}return root;}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}// Time Complexity : O(n)// Space Complexity : O(1)
C++
#include <bits/stdc++.h>using namespace std;struct ListNode{int val;ListNode *next;ListNode(int data){this->val=data;this->next=NULL;}};void linkedListTraversal(ListNode *node){while (node != NULL) {cout<<node->val<<" ";node = node->next;}}ListNode* removeElement(ListNode *head, int n){// If list is nullif (head == NULL) {return head;}ListNode *root = head;// if deleted element in beginningwhile (root != NULL) {// if found then deleteif (root->val == n) {root = root->next;} else {break;}}ListNode *prev = root;ListNode *prev1 = root;while (prev !=NULL) {// if found nth then deletewhile (prev !=NULL && prev->val == n) {prev1->next = prev->next;prev = prev->next;}// change previousprev1 = prev;if (prev !=NULL)prev = prev->next;}return root;}int main(){ListNode *head = new ListNode(1);head->next = new ListNode(2);head->next->next = new ListNode(6);head->next->next->next = new ListNode(3);head->next->next->next->next = new ListNode(4);head->next->next->next->next->next = new ListNode(5);head->next->next->next->next->next->next = new ListNode(6);int val = 6;ListNode *node = removeElement(head, val);cout<<"After Removing :\n";linkedListTraversal(node);}// Time Complexity : O(n)// Space Complexity : O(1)
No comments:
Post a Comment