问题
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