Example
Input: 5->2->8->4->1->NULL , node=8 Output: 5->2->4->1
Approach:
Java
public class DeleteNodeLinkedListWithoutHead {public static void main(String[] args) {ListNode l = new ListNode(5);l.next = new ListNode(2);l.next.next = new ListNode(8);ListNode node = new ListNode(4);l.next.next.next = node;l.next.next.next.next = new ListNode(5);deleteNode(node);linkedListTraversal(l);}// method to delete node without headprivate static void deleteNode(ListNode node) {ListNode tmp = node.next;node.val = tmp.val;node.next = tmp.next;}// traversal linked listprivate static void linkedListTraversal(ListNode node) {while (node != null) {System.out.print(node.val + " ");node = node.next;}}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//function to traverse(print) a linked//listvoid linkedListTraversal(Node *head){Node *temp=head;//iterate till we reach end of the linked//listwhile(temp!=NULL){//print the current//node datacout<<temp->data<<" ";//move to next nodetemp=temp->next;}}//function to delete the node//without headvoid deleteNode(Node *node){//base case if not NULLif(node==NULL)return;if(node->next==NULL){return;}else{//varible to hold the next//of nodeNode *temp;temp=node->next;//copy data of temp//into nodenode->data=temp->data;//make pointer of node to//next of tempnode->next=temp->next;//free tempdelete temp;}}int main(){Node *head=new Node(5);head->next=new Node(2);head->next->next=new Node(8);head->next->next->next=new Node(4);head->next->next->next->next=new Node(1);Node *node=head->next->next; //i.e 8deleteNode(node);cout<<"List After delete\n";linkedListTraversal(head);return 0;}
No comments:
Post a Comment