I want to enter the number at a particular position but my code is not putting the element in the required position, it seems right to me because I manually doing it in the Paper but in the system, I can't get the element in that position. It insert an element at the end of the list rather than specific position.
My Code
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* next;
};
void beginning(struct Node** head_ref, int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head_ref;
*head_ref = newNode;
}
int lenght(struct Node* head_ref)
{
int count = 0;
struct Node* current = head_ref;
while(current != NULL)
{
count++;
current = current->next;
}
return count;
}
void middle(struct Node* head_ref, int data, int position)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
int size = lenght(head_ref);
if(size > position)
{
for(int i = 0; i < size-1; i++)
{
head_ref = (head_ref->next);
}
newNode->next = head_ref->next;
head_ref->next = newNode;
}
}
void end(struct Node** head_ref, int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;
newNode->data = data;
newNode->next = NULL;
if(*head_ref==NULL)
{
*head_ref = newNode;
return;
}
while(last->next != NULL)
{
last = last->next;
}
last->next = newNode;
}
void printlist(struct Node* head_ref)
{
int i;
while(head_ref != NULL)
{
printf("%d ", head_ref->data);
head_ref = head_ref->next;
}
}
int main()
{
struct Node* head = NULL;
int choices, element, index;
char insertionChoices;
while(1)
{
printf("
Enter your choices:
1.Enter an element in the beginning
2.Enter the element in the middle
"
"3.Enter the element at the end
4. Traverse
5. Exit
");
scanf("%d", &choices);
switch(choices)
{
case 1:
printf("Enter an element: ");
scanf("%d", &element);
beginning(&head, element);
break;
case 2:
printf("Enter an index and elemetn: ");
scanf("%d %d", &index, &element);
middle(head, element, index-1);
break;
case 3:
printf("Enter an element: ");
scanf("%d", &element);
end(&head, element);
break;
case 4:
printlist(head);
break;
case 5:
exit(0);
default:printf("Wrong input");
}
}
return 0;
}
question from:
https://stackoverflow.com/questions/65682022/cant-insert-the-element-in-the-required-position 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…