Efficiently finding nth from last element in a linked list

别等时光非礼了梦想. 提交于 2019-12-13 17:16:38

问题


What is an efficient way of finding nth from last element in a singly/doubly linked list?


回答1:


Here's an efficient way of finding nth from last element in a linked list.

struct Node{
    int data;
    struct Node *next;
};

int getNthFromLast(struct Node *head, int n){
    struct Node *curr = head;
    struct Node *nthFromLast=NULL;
    int count=0;
    int value=-1;
    while(curr!=NULL){
        count++;
        curr=curr->next;
        if(count==n){
            nthFromLast=head;
        }else
            if(count>n){
                nthFromLast=nthFromLast->next;
            }
    }
    if(count>=n){
        value=nthFromLast->data;
    }
    return value;
}

This example has been written in C++ and can be replicated similarly in other languages. The method is passed a pointer to the first node of the linked list and the index from last element, whose data it returns. If the position is not present, the method returns -1.

Similar approach can be taken in case of a doubly linked list as well as circular linked list.

EDIT: In case of a doubly linked list, just move n items in reverse. Totally forgot about that. Credits: Jim Mischel



来源:https://stackoverflow.com/questions/40724339/efficiently-finding-nth-from-last-element-in-a-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!