-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindNthElement.cpp
59 lines (56 loc) · 1.05 KB
/
FindNthElement.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
#include <bits/stdc++.h>
using namespace std;
typedef struct node {
int data;
node *next;
} node;
node* init(int a[], int n) {
node *head, *p;
for (int i = 0; i < n; ++i) {
node *nd = new node();
nd->data = a[i];
if (i == 0) {
head = p = nd;
continue;
}
p->next = nd;
p = nd;
}
return head;
}
node* findNthToLast(node *head, int n) {
if (head == NULL || n < 1) return NULL;
node *p = head, *q = head;
while (n > 0 && q) {
q = q->next;
--n;
}
if (n > 0) return NULL;
while (q) {
p = p->next;
q = q->next;
}
return p;
}
node *pp;
int nn;
void findNthToLast1(node *head) {
if (head == NULL) return;
findNthToLast1(head->next);
if (nn == 1) pp = head;
--nn;
}
int main() {
int n = 10;
int a[] = {
1, 2, 3, 4, 35, 6, 7, 8, 9, 10
};
node *head = init(a, n);
node *p = findNthToLast(head, 6);
if (p) cout << p->data << endl;
else cout << "the length of link is not long enough" << endl;
nn = 6;
findNthToLast1(head);
if (pp) cout << pp->data << endl;
return 0;
}