问题来源:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
/**
*
* <p>
* ClassName RemoveNthNodeFromEndOfList
* </p>
* <p>
* Description Given a linked list, remove the nth node from the end of list and return its head.
*
* For example,
*
* Given linked list: 1->2->3->4->5, and n = 2.
*
* After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do
* this in one pass.
* </p>
*
* @author TKPad wangx89@126.com
* <p>
* Date 2015年3月26日 下午11:07:52
* </p>
* @version V1.0.0
*
*/
public class RemoveNthNodeFromEndOfList {
public ListNode removeNthFromEnd(ListNode head, int n) {
if (0 == n) {
return head;
}
if (head.next == null) {
return null;
}
ListNode p = head;
ListNode q = head;
while (n != 0) {
q = q.next;
n--;
/*
* if n equals to the number of nodes, that means remove the first node, so just let the head to be the head.next.
*/
// 处理n没有走完的情况,说明链表的长度肯定是<=n,所以移除head
if (q.next == null && n != 0) {
head = head.next;
return head;
}
}
// 处理p后移的问题,保证p和q之间有n个节点,这样移除p之后的一个节点即可
while (q.next != null) {
q = q.next;
p = p.next;
}
// 处理移除末尾节点
if (n == 1) {
p.next = null;
return head;
} else {
p.next = p.next.next;
return head;
}
}
public static void main(String[] args) {
// Input: {1,2}, 2
// Output: {1}
// Expected: {2}
// Input: {1,2}, 1
// Output: {}
// Expected: {1}
// Input: {1}, 1
// Output: {1}
// Expected: {}
// Input: {1,2,3}, 3
// Output: {1,3}
// Expected: {2,3}
// Input: {1,2,3}, 2
// Output: {2,3}
// Expected: {1,3}
ListNode ln = new ListNode(1);
ListNode ln2 = new ListNode(2);
ListNode ln3 = new ListNode(3);
// ListNode ln4 = new ListNode(4);
ln.next = ln2;
ln2.next = ln3;
// ln3.next = ln4;
ListNode removeNthFromEnd = new RemoveNthNodeFromEndOfList().removeNthFromEnd(ln, 0);
System.out.println(removeNthFromEnd.val);
System.out.println(removeNthFromEnd.next.val);
System.out.println(removeNthFromEnd.next.next);
}
}