-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsgLLfindnth.cpp
More file actions
73 lines (71 loc) · 1.2 KB
/
sgLLfindnth.cpp
File metadata and controls
73 lines (71 loc) · 1.2 KB
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
//Find the Nth node from the end of a singly linked list in one traversal
#include<iostream>
#include<string>
using namespace std;
#define null 0
struct node
{
string data;
node *next;
};
node *first,*temp,*ttemp,*i,*j;
void init()
{
first=temp=ttemp=null;
}
void addnode()
{
ttemp=new node;
cin>>ttemp->data;
ttemp->next=null;
if(first==null)
first=ttemp;
else
temp->next=ttemp;
temp=ttemp;
}
void disp()
{
temp=first;
while(temp!=null)
{
cout<<temp->data<<"\n";
temp=temp->next;
}
}
node*findingNth_from_last(node*head,int N)
{
node*p=head;
node*q=head;
for(int i=0;i<N;i++)
{
p=p->next;
}
while(p)
{
p=p->next;
q=q->next;
}
return q;
}
int main()
{
init();
int n,loopPos;
cout<<"enter number of names u want to enter: ";
cin>>n;
for(int i=1;i<=n;i++)
{
addnode();
}
cout<<"\noriginal sequence\n";
disp();
int N;
cout<<"enter the position of node: ";
cin>>N;
node*val=findingNth_from_last(first,N);
if (val)
cout << "Nth node from end is: " << val->data << endl;
else
cout << "Invalid N — exceeds list length.\n";
}