题解 | #删除链表的倒数第n个节点#

删除链表的倒数第n个节点

http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6

public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode slow = head;
ListNode fast = head;
for(int i=0;i<n;i++){
fast = fast.next;
}
while(fast!=null && fast.next!=null){
fast = fast.next;
slow = slow.next;
}
if(fast == null){
return slow.next;
}
slow.next = slow.next.next;
return head;
}
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务