-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathKthNodeFromEnd.cpp
59 lines (59 loc) · 1.22 KB
/
KthNodeFromEnd.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
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* head, unsigned int k) {
if (head==NULL || k<=0)
return NULL;
int n = 0;
for (ListNode* temp = head;temp!=NULL;temp=temp->next)
{
n++;
}
if (n<k) return NULL;
ListNode* p = head;
for (int i=0;i<n-k;i++)
{
p = p->next;
}
return p;
}
};
// Solution 2:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* head, unsigned int k) {
if (head==NULL || k<=0)
return NULL;
ListNode* p = head;
ListNode* q = head;
// 从第1一个节点开始计数,所以走k-1步到达k节点,注意判断k是否超过链表总长度
for (int i=0;i<k-1;i++)
{
if (q->next!=NULL)
q = q->next;
else
return NULL;
}
while(q->next!=NULL)
{
p = p->next;
q = q->next;
}
return p;
}
};