[LeetCode

来源:互联网 发布:淘宝商品佣金查询 编辑:程序博客网 时间:2024/06/16 05:04

1 问题

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.

2 分析

leetCode 网站提供完整的答案,这里只记录下dummy head的作用, The “dummy” node is used to simplify some corner cases:

  • such as a list with only one node.
  • removing the head of the list.

3 代码

public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        ListNode dummyNode = new ListNode(0);        dummyNode.next = head;        ListNode left = dummyNode;        ListNode right = dummyNode;        int idx = 0;        while(right.next != null ){            if(idx >= n){                left = left.next;            }            right = right.next;            idx++;        }        left.next = left.next.next;        return dummyNode.next;    }}