-
Notifications
You must be signed in to change notification settings - Fork 0
/
Print Nth node from end in singly linked list.cpp
76 lines (68 loc) · 1.22 KB
/
Print Nth node from end in singly linked list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node *next;
Node(int data)
{
this->data=data;
next=NULL;
}
};
Node* add(Node *head,int data)
{
Node* temp=new Node(data);
if(head==NULL)
{
head=temp;
}
else{
Node *trav=head;
while(trav->next!=NULL)
{
trav=trav->next;
}
trav->next=temp;
}
return head;
}
void printNthFromEnd(Node* head, int n) {
Node *slow = head;
Node *fast = head;
int count = 0;
if(head != NULL)
{
while( count < n )
{
if(fast == NULL)
{
cout<<"N is greater than size of linkedlist.\n";
return;
}
fast = fast->next;
count++;
} /* End of while*/
while(fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
cout<<"Nth node from end is:"<<slow->data;
}
}
int main()
{
Node *head=NULL;
int n,k;
cout<<"enter the size of linkedlist and k :";
cin>>n>>k;
for(int i=0; i<n; i++)
{
int element;
cin>>element;
head=add(head,element);
}
printNthFromEnd(head,k);
return 0;
}