LeetCode_19---Remove Nth Node From End of List

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.

翻译:

    Code:



    /**
     * @author MohnSnow
     * @time 2015年6月5日 下午2:27:01
     * 
     */
    public class LeetCode19 {
    
    	static class ListNode {
    		int			val;
    		ListNode	next;
    
    		ListNode(int x) {
    			val = x;
    		}
    
    		@Override
    		public String toString() {
    			if (this.next != null) {
    				return val + "---" + this.next.toString();
    			} else {
    				return val + "";
    			}
    		}
    	}
    //304msA
    	public static ListNode removeNthFromEnd(ListNode head, int n) {
    		if(n == 0){
    			return head;
    		}
    		System.out.println("删除倒数第 " + n + " 个");
    		int i = 1;
    		ListNode iNode = head;
    		ListNode jNode = head;
    		while (iNode.next != null) {
    			iNode = iNode.next;
    			i++;
    			if (i > n + 1) {
    				jNode = jNode.next;
    			}
    		}
    		System.out.println("jNode是:  "+jNode);
    		if (i >= n) {
    			if (jNode == head&&i==n) {
    				System.out.println("删除第一个:");
    				return head.next;//删除第一个
    			} else {				
    				System.out.println("删除倒数第N个:");
    				jNode.next = jNode.next.next;
    				return head;
    			}
    		} else {
    			System.out.println("N太大,不做删除:");
    			return head;//n大于长度,不做删除
    		}
    	}
    
    	public static void main(String[] args) {
    		ListNode a = new ListNode(1);
    		ListNode b = new ListNode(2);
    		ListNode c = new ListNode(3);
    		ListNode d = new ListNode(4);
    		ListNode e = new ListNode(5);
    		a.next = b;
    		b.next = c;
    		c.next = d;
    		d.next = e;
    		e.next = null;
    		System.out.println(removeNthFromEnd(a, 0));
    	}
    
    }
    







    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值