-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19.RemoveNthFromEnd.cs
42 lines (41 loc) · 989 Bytes
/
19.RemoveNthFromEnd.cs
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
// 19. Remove Nth Node From End of List
// Given the head of a linked list, remove the nth node from the end of the list and return its head.
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode p,q,t;
t= null;
p = q = head;
for(int i= 0; i<n ; i++){
p = p.next;
}
while(p!=null){
p=p.next;
t=q;
q=q.next;
}
if (t==null){
head = head.next;
}
else if(q==null){
t = null;
}
else if(q.next == null){
t.next = null;
}
else{
t.next= t.next.next;
}
return head;
}
}