单次循环
删除链表的倒数第n个节点
http://www.nowcoder.com/questionTerminal/f95dcdafbde44b22a6d741baf71653f6
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode slow = head,fast = head,pre = null;
if(head.next == null){
return null;
}
while(fast != null){
fast = fast.next;
if(n == 0){
pre = slow;
slow = slow.next;
}else{
n--;
}
}
ListNode current = head;
if(slow == head){
return head.next;
}else{
pre.next = pre.next.next;
return head;
}
}
}
查看9道真题和解析