您的位置:首页 > Web前端 > Node.js

Leetcode 19.Remove Nth Node From End of List

2016-12-14 20:09 405 查看
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.
要从list的末端进行删除 关键的问题是怎么找到那个node的位置 也就是数出(length - n)个数
同时可以逆向思维 n = length - 要挪动的节点数

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
   public ListNode removeNthFromEnd(ListNode head, int n) {
    
    ListNode start = new ListNode(0);
    ListNode point2 = start, point1 = start;
    start.next = head;//这样目前两个指针都指向了同样的节点
    
   
    for(int i=1; i<=n+1; i++)   {
        point1 = point1.next;
    }
   
    while(point1 != null) {
        point2 = point2.next;
        point1 = point1.next;
    }
   
    point2.next = point2.next.next;
    return start.next;
}
}


So brilliant!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: