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

Leetcode#19||Remove Nth Node From End of List

2015-08-12 12:17 615 查看
/**
* 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) {
if (head == null || n <= 0) {
return head;
}

ListNode dummy = new ListNode(-1);
dummy.next = head;

ListNode fast = dummy;
ListNode slow = dummy;

for (int i = 1; i <= n; i++) {
fast = fast.next;
}

while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}

slow.next = slow.next.next;

return dummy.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息