Title Description:
Enter a list to output the last K nodes in the linked list.
(Hint: Be sure to use a linked list.) )
Input:
The input may contain multiple test samples, and the input ends with EOF.
For each test case, enter the first behavior of two integers n and K (0<=n<=1000, 0<=k<=1000): N represents the number of linked list elements that will be entered, and K represents the element to query the penultimate number.
The second line of input includes n number T (1<=t<=1000000): Represents the element in the linked list.
Output:
corresponding to each test case,
If there is a result, the corresponding search results are output. Otherwise, the output is null.
Sample Input:
5 2
1 2 3 4 5
1 0
5
Sample output:
4
NULL
Analysis:
The penultimate k, is the positive number n-k+1
AC Code:
#include <stdio.h> #include <stdlib.h> typedef struct Node {int data;
struct node *next;
} linklist;
int main () {int i, n, M, K;
Linklist *head, *tail, *p;
while (scanf ("%d%d", &n, &k)! = EOF) {head = (linklist *) malloc (sizeof (linklist));
tail = head;
Head->next = NULL;
for (i = 0; i < n; i++) {scanf ("%d", &m);
p = (linklist *) malloc (sizeof (linklist));
P->data = m;
P->next = NULL;
Tail->next = p;
tail = p;
} if (k > N | | k < 1) {printf ("null\n");
} else {p = head->next;
/* Count K, positive number n-k+1: */for (i = 0; i < n-k; i++) {p = p->next;
} printf ("%d\n", p->data);
} free (p);
Free (head);
} return 0; }
/***********************************************problem:1517 user:wusuopubupt language:c result:accepted time:100 Ms Memory:24 KB ****************************************************************/