n개의 노드가 있는 경우 작업은 연결 목록의 끝에서 n번째 노드를 인쇄하는 것입니다. 프로그램은 목록에서 노드의 순서를 변경해서는 안 됩니다. 대신 연결 목록의 마지막에서 n번째 노드만 인쇄해야 합니다.
예시
Input -: 10 20 30 40 50 60 N=3 Output -: 40
위의 예에서 첫 번째 노드에서 시작하여 count-n개의 노드(예:10,20 30,40, 50,60)까지 이동하므로 마지막 노드에서 세 번째 노드는 40입니다.

전체 목록을 탐색하는 대신 이 효율적인 접근 방식을 따를 수 있습니다 -
- 임시 포인터, 예를 들어 노드 유형의 temp
- 이 임시 포인터를 헤드 포인터가 가리키는 첫 번째 노드로 설정
- 목록의 노드 수로 카운터 설정
- temp를 temp로 이동 → count-n까지 다음
- 디스플레이 온도 → 데이터
이 접근 방식을 사용하면 than count는 5가 되고 프로그램은 5-3, 즉 2까지 루프를 반복하므로 0 번째 에 10부터 시작합니다. 1 st 의 20보다 위치 위치 및 2 nd 30 결과인 위치입니다. 따라서 이 접근 방식을 사용하면 전체 목록을 끝까지 탐색할 필요가 없으므로 공간과 메모리가 절약됩니다.
알고리즘
Start Step 1 -> create structure of a node and temp, next and head as pointer to a structure node struct node int data struct node *next, *head, *temp End Step 2 -> declare function to insert a node in a list void insert(int val) struct node* newnode = (struct node*)malloc(sizeof(struct node)) newnode->data = val IF head= NULL set head = newnode set head->next = NULL End Else Set temp=head Loop While temp->next!=NULL Set temp=temp->next End Set newnode->next=NULL Set temp->next=newnode End Step 3 -> Declare a function to display list void display() IF head=NULL Print no node End Else Set temp=head Loop While temp!=NULL Print temp->data Set temp=temp->next End End Step 4 -> declare a function to find nth node from last of a linked list void last(int n) declare int product=1, i Set temp=head Loop For i=0 and i<count-n and i++ Set temp=temp->next End Print temp->data Step 5 -> in main() Create nodes using struct node* head = NULL Declare variable n as nth to 3 Call function insert(10) to insert a node Call display() to display the list Call last(n) to find nth node from last of a list Stop
예시
#include<stdio.h>
#include<stdlib.h>
//structure of a node
struct node{
int data;
struct node *next;
}*head,*temp;
int count=0;
//function for inserting nodes into a list
void insert(int val){
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = val;
newnode->next = NULL;
if(head == NULL){
head = newnode;
temp = head;
count++;
} else {
temp->next=newnode;
temp=temp->next;
count++;
}
}
//function for displaying a list
void display(){
if(head==NULL)
printf("no node ");
else {
temp=head;
while(temp!=NULL) {
printf("%d ",temp->data);
temp=temp->next;
}
}
}
//function for finding 3rd node from the last of a linked list
void last(int n){
int i;
temp=head;
for(i=0;i<count-n;i++){
temp=temp->next;
}
printf("\n%drd node from the end of linked list is : %d" ,n,temp->data);
}
int main(){
//creating list
struct node* head = NULL;
int n=3;
//inserting elements into a list
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
insert(6);
//displaying the list
printf("\nlinked list is : ");
display();
//calling function for finding nth element in a list from last
last(n);
return 0;
} 출력
linked list is : 1 2 3 4 5 6 3rd node from the end of linked list is : 4