forked from Jensenczx/CodeEveryday
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path43_removeNthFromEnd.java
More file actions
35 lines (35 loc) · 858 Bytes
/
43_removeNthFromEnd.java
File metadata and controls
35 lines (35 loc) · 858 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
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode removeNthFromEnd(ListNode head, int n) {
// write your code here
if(head==null)
return null;
if(n<=0)
return head;
ListNode tmp = head;
ListNode result = head;
for(int i=0; i<n; i++)
tmp = tmp.next;
ListNode preNode = head;
while(tmp!=null){
tmp = tmp.next;
preNode = head;
head = head.next;
}
if(head.next==null){
if(head==preNode)
result = null;
else
preNode.next = null;
}
else{
head.val = head.next.val;
head.next = head.next.next;
}
return result;
}
}