-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveNthNodeFromEndofList.cpp
More file actions
executable file
·71 lines (58 loc) · 1.18 KB
/
RemoveNthNodeFromEndofList.cpp
File metadata and controls
executable file
·71 lines (58 loc) · 1.18 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
//
// RemoveNthNodeFromEndofList.cpp
// leetcode
//
// Created by witwolf on 5/5/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
/**
* Definition for singly-linked list.
*/
#include <stdio.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
if(n <= 0 || head == NULL){
return head;
}
struct ListNode *first = head,*second=head,*prev = NULL ;
while(n && second){
second = second->next;
n -- ;
}
if(n){
return head;
}
while (second) {
prev = first;
first = first->next;
second = second->next;
}
if(first == head){
head = head->next;
}else{
prev->next = first->next;
}
delete first;
return head;
}
void print(struct ListNode *head){
while(head){
printf("%d->",head->val);
head = head->next;
}
printf("NULL\n");
}
int main(int argc,char **argv){
struct ListNode n1,n2,n3;
n1.val = 1;
n1.next = &n2;
n2.val = 2;
n2.next = &n3;
n3.val = 3;
n3.next = NULL;
print(&n1);
print(removeNthFromEnd(&n1, 1));
}