I made a code of deleting a node by its address only and the function deleteNode
is deleting the node at that position but it is deleting more values and I am not being able to delete the last node.
#include<bits/stdc++.h>
using namespace std;
struct Node { //node defination
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
}*head;
Node *findNode(Node* head, int search_for) //find the node that will delete
{
Node* current = head;
while (current != NULL)
{
if (current->data == search_for)
break;
current = current->next;
}
return current;
}
void insert() //insert the values in node
{
int n,i,value;
Node *temp;
scanf("%d",&n);
for(i=0; i<n; i++)
{
scanf("%d",&value);
if(i==0)
{
head=new Node(value);
temp=head;
continue;
}
else
{
temp->next= new Node(value);
temp=temp->next;
temp->next=NULL;
}
}
}
void printList(Node *node) //print the value in node
{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
cout << endl;
}
void deleteNode(Node *node_ptr);
int main(void) //main starts from here
{
int k,n,value;
{
insert();
scanf("%d",&k);
Node *del = findNode(head, k);
if (del != NULL && del->next != NULL)
{
deleteNode(del);
}
printList(head);
}
return(0);
}
void deleteNode(Node *pos) //delete node function
{
struct Node *temp;
while(temp->next!=0)
{
temp=pos->next;
pos->data=temp->data;
pos->next=temp->next;
pos=temp;
}
}
Input
5 (size of a linked list)
1 2 3 4 5 (elements of list)
2 (position to delete)
Expected output
1 3 4 5
Current output
1 3 5