Remove Nth Node From End of List

问题来源: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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值