List of the last K nodes in a list

Source: Internet
Author: User
Tags printf

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 ****************************************************************/ 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.