每天一题LeetCode[第十一天]

来源:互联网 发布:搞笑特效软件 编辑:程序博客网 时间:2024/05/23 19:48

每天一题LeetCode[第十一天]


Remove Nth Node From End of List

Description:

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.Subscribe to see which companies asked this question.

翻译:

给一个链表,从最后一个当作第一个,删除第n个节点,再把最后的结果返回。例子:  给一个链表:1->2->3->4->5 n=2  在删除晚第n个节点后,链表为1->2->3->5注意:n值永远是合法的。尝试只要一次循环给出正确结果。 

解题思路:

  • 一开始题意理解错误,所以想不明白为什么这种难度的要设置成medium。以至于后面看Top Solution的时候,看不明白什么意思。又回过来看了一下题目,终于明白了。从后面算n个,难度在于你不知道总长度,还要倒着找第n个,要求只能循环一遍。

  • 又在看了一遍Top Solution一下子明白了,原来如此,对于长度未知,但需要从后面倒着的需求,可以有这种解法:先让一个pointer走n步,在让另外一个节点从开始节点起步,两个pointers以相同的速度前进,这样两个pointer间距n个节点,当最后一个pointer到达节点,第一个pointer也就在从后往前数的第n个节点啦。


Java代码:

public class ListNode {    int val;    ListNode(int x) {        val = x;    }    ListNode next;}public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        ListNode start=new ListNode(0);        ListNode fast=start,slow=start;        slow.next=head;        for(int i=1;i<=n+1;i++){            fast=fast.next;        }        while (fast!=null){            fast=fast.next;            slow=slow.next;        }        slow.next=slow.next.next;        return start.next;    }}

提高代码质量就是:积累精致的思路,优质的细节。

0 0
原创粉丝点击