试图解决Hackerrank中的挑战(倒数第M个元素)



此处给出了问题的链接:https://www.hackerrank.com/contests/programming-interview-questions/challenges/m-th-to-last-element/problem

我基本上是想在C编程中从链表的末尾找到第m个元素。我已经在IDE中实现了代码,它运行良好(需要一些微调(,但在Hackerrank中不起作用。我无法解决这个问题。我可能认为在读取代码中的输入时存在问题。我得到的输出是"~stdout上没有响应~";。我真的很感谢任何关于如何克服这一点的帮助,因为我不熟悉在hackerbank中解决挑战。如果我遗漏了什么,请指出。如果需要,请查看所附链接以了解问题说明。我在下面附上了我的代码供您参考。非常感谢。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
struct node *head;
int count;
struct node
{
long int data;
struct node* next;
struct node* prev;
};
void Insert(long int val)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
if(count == 0)
{
temp->next = NULL;
temp->prev = NULL;
temp->data = val;
head = temp;
}
else
{
struct node* temp1 = head;
temp->next = temp1;
temp->prev = NULL;
temp->data = val;
temp1->prev = temp;
head = temp;
}
count++;
}
void Mthelement(long int M)
{
long int i = 0;
struct node* temp = head;
while(temp->next != NULL)
{
temp = temp->next;
}
if (M == 1)
{
printf("%ld", temp->data);
}
else
{
while(i < (M-1))
{
if(temp->prev == NULL)
{
printf("NIL");
return;
}
temp = temp->prev;
i++;
}
printf("%ld", temp->data);
}
}

int main() {
head = NULL;
long int M,L;
printf("Enter value of M: ");
scanf("%ld", &M);
printf("Enter value of L: ");
while(scanf("%ld", &L))
{
Insert(L);
}
Mthelement(M);
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}

我找到了问题的解决方案。看来我所要做的就是像这样写代码while(scanf("%d",&L(==1(以便在hackerlink中获取未知数量的输入。感谢大家抽出时间。

最新更新