Access Kth to the last element in Linked List
/***
Implement an algorithm to find the kth to last element to a singly linked list.
***/
#include<iostream>
using namespace std;
#define K 8
struct ListNode {
int value;
ListNode *next;
};
int find_Kth_tolast(ListNode *list) {
ListNode *sptr, *fptr;
sptr = list;
fptr = list;
for(int i=0; i<K; i++) {
if(fptr != NULL) fptr = fptr->next;
else {
cout << "length of list is less than K"<<endl;
return sptr->value;
}
}
while (fptr->next != NULL) {
fptr = fptr->next;
sptr = sptr->next;
}
return sptr->value;
}
Implement an algorithm to find the kth to last element to a singly linked list.
***/
#include<iostream>
using namespace std;
#define K 8
struct ListNode {
int value;
ListNode *next;
};
int find_Kth_tolast(ListNode *list) {
ListNode *sptr, *fptr;
sptr = list;
fptr = list;
for(int i=0; i<K; i++) {
if(fptr != NULL) fptr = fptr->next;
else {
cout << "length of list is less than K"<<endl;
return sptr->value;
}
}
while (fptr->next != NULL) {
fptr = fptr->next;
sptr = sptr->next;
}
return sptr->value;
}
Comments
Post a Comment