작업은 재귀 접근 방식을 사용하여 연결 목록의 끝에서 시작하여 k 노드를 인쇄하는 것입니다.
재귀 접근 방식은 함수가 호출될 때까지 계속해서 자신을 호출하여 결과를 저장하는 방식입니다.
목록에 노드 29, 34, 43, 56 및 88이 포함되어 있고 k 값이 2인 경우 출력은 56 및 88과 같은 마지막 k 노드가 됩니다.

예시
Linked List: 29->34->43->56->88 Input: 2 Output: 88 56
지정된 대로 재귀 접근 방식을 사용하여 목록을 순회할 횟수를 추적하면서 끝에서 목록을 순회해야 하며 재귀 함수는 포인터 변수에 의해 k번째 값까지 호출됩니다.
아래 코드는 주어진 알고리즘의 c 구현을 보여줍니다.
알고리즘
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *next Step 2 -> Declare function as node* get(int data) Create newnode using malloc function Set newnode->data = data Set newnode->next = NULL return newnode step 3 -> Declare function void lastval(node* head, int& count, int k) IF !head Return Set lastval(head->next, count, k) Set count++ IF (count <= k) Print head->data Step 4 -> In Main() Generate head using node* head = get(11) Set k and count to 0 Call lastval(head,k,count) STOP
예시
#include<stdio.h>
#include<stdlib.h>
// Structure of a node
struct node {
int data;
node* next;
};
// Function to get a new node
node* get(int data) {
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
//print the last k values of a node
void lastval(node* head, int& count, int k) {
if (!head)
return;
lastval(head->next, count, k);
count++;
if (count <= k)
printf("%d ", head->data);
}
int main() {
node* head = get(11); //inserting elements into the list
head->next = get(243);
head->next->next = get(321);
head->next->next->next = get(421);
head->next->next->next->next = get(522);
int k = 2, count = 0;
printf(" last %d nodes of a list are :",k);
// print last k nodes
lastval(head, count, k);
return 0;
} 출력
위의 프로그램을 실행하면 다음과 같은 출력이 생성됩니다.
last 2 nodes of a list are :522 421