/**
* 给定一个链表,删除链表的倒数第n个节点并返回链表的头指针
* 例如,
* 给出的链表为:1->2->3->4->5, n= 2.↵↵
* 删除了链表的倒数第n个节点以后,链表变为1->2->3->5.
* 备注:
* 题目保证n必定是合法的
* 请尝试只用一步操做完成该功能
*/
public class Main58 {
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
System.out.println(Main58.removeNthFromEnd(head, 2).val);
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode first = head;
ListNode second = head;
while (n-- > 0) {
first = first.next;
}
ListNode pre = null;
while (first.next != null) {
pre = second;
second = second.next;
first = first.next;
}
if (pre != null) {
pre.next = second.next;
}else{
head = head.next;
}
return head;
}
}