Code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
NODE *create()
{
return NULL;
}
int insert(int val, NODE *List);
void displayList();
int Length(NODE *head);
int deleteNode(NODE *List, int x);
int main()
{
NODE *L = create();
int val, p, choice, dp;
char again;
while(choice!=4)
{
clrscr();
displayList(L);
printf("\nMENU\n[1] Insert\n[2] View\n[3] Delete\n[4] Exit\n");
printf("\nChoice? ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("\nValue to insert? ");
scanf("%d", &val);
L = insert(val, L);
getch();
break;
case 2:
displayList(L);
getch();
break;
case 3:
printf("\nValue to delete: ");
scanf("%d", &dp);
L = deleteNode(L, dp);
getch();
break;
case 4:
return 0;
default:
printf("\nINVALID INPUT!\n");
break;
}
}
}
/***************************************************************/
void displayList(NODE *List)
{
if(List==NULL)
{
printf("There are no elements in the list!!");
}
else
{
while(List!=NULL)
{
printf ("%d -> ", List->data);
List=List->next;
}
}
}
/***************************************************************/
int insert(int val, NODE *List)
{
NODE *new;
new = (NODE*)malloc(sizeof(NODE));
if (new)
{
new -> data = val;
new ->next = NULL;
if(List==NULL)
{
List=new;
}
else
{
new -> next = List;
List = new;
}
}
printf("\nInsert successful!\n");
return List;
}
/***************************************************************/
int Length(NODE *head)
{
NODE *current = head;
int count = 0;
while (current != NULL)
{
count ++;
current = current -> next;
}
return count;
}
int deleteNode(NODE *List, int x)
{
NODE *tmp;
tmp = List;
if(tmp==NULL)
printf("List is empty!");
else
{
while(tmp->data!=x)
{
tmp = tmp ->next;
}
free(tmp);
tmp = tmp ->next;
}
return tmp;
}
The above code is a SLL.
I have a problem in my deleteNode function.
I can't delete the exact data on the list.
Can anybody help me how to do this right?
Thanks