题目描述:
给定一个链表,删除链表的倒数第n个节点并返回链表的头指针
例如:
给出的链表为:1->2->3->4->5, n= 2.
删除了链表的倒数第n个节点之后,链表变为1->2->3->5.
输入
{1,2},2
返回值
{2}
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
if(head == null){
return null;
}
ListNode pre = new ListNode(0);
pre.next = head;
ListNode start = pre,end = pre;
while(n != 0){
start = start.next;
n--;
}
while(start.next != null){
start = start.next;
end = end.next;
}
end.next = end.next.next;
return pre.next;
}
}