forked from changqing16/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19.cpp
More file actions
54 lines (48 loc) · 988 Bytes
/
19.cpp
File metadata and controls
54 lines (48 loc) · 988 Bytes
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
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *removeNthFromEnd(ListNode *head, int n)
{
ListNode *first = head, *second = head;
int length = 0;
while (first != NULL)
{
if (length - n > 0)
second = second->next;
length++;
first = first->next;
}
if (second == head && length == n)
return head->next;
else
{
ListNode *tmp = second->next;
second->next = tmp->next;
return head;
}
}
int main()
{
ListNode *head;
head = new ListNode(1);
ListNode *p = head;
for (int i = 0; i < 2; i++)
{
ListNode *now = new ListNode(i + 2);
p->next = now;
p = p->next;
}
ListNode *ans = removeNthFromEnd(head, 2);
while (ans != NULL)
{
printf("%d ", ans->val);
ans = ans->next;
}
}