LeetCode 019 Remove Nth Node From End of List

来源:互联网 发布:java课程设计小游戏 编辑:程序博客网 时间:2024/05/17 01:24
题目


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.

链表中倒数第n个给删除。


思路


1 条件中,n永远合法,所以减少了错误判断所需的内容。

2 第一次last,先记录 离head n的节点在哪。

3 第二次,保留一个pre , pre 和 last同时前进,这样,当last指向最后一个节点的时候,pre正好是所要删除的节点的前一个节点。

4 进行删除操作。


代码


public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        if(head==null){            return null;        }        ListNode dummy = new ListNode(Integer.MIN_VALUE);        dummy.next = head;        ListNode last =dummy;        for(int i=0;i<n;i++){            last = last.next;        }        ListNode pre = dummy;        while(last.next!=null){            last=last.next;            pre=pre.next;        }        pre.next = pre.next.next;        return dummy.next;    }}



0 0
原创粉丝点击