[leetCode]Remove Nth Node From End of List

来源:互联网 发布:网口数据监控软件 编辑:程序博客网 时间:2024/06/06 00:11

题目描述如下:

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.

分析思路:

原本采用的是先遍历一次得到链表的长度,然后根据得到的长度进行二次遍历删除,提交后可以通过,但是没有满足只遍历一次的要求。于是,采用双指针的思想,为了正确定位到要删除的位置,因此,需要前指针start与后指针end的位置相差n,start指向的就是待删除节点的父节点。注意如果是删除头结点时的条件判断。

代码如下:

public class Solution {    public ListNode removeNthFromEnd(ListNode head, int n) {        if(head==null)return head;        ListNode start,end;        start=new ListNode(-1);        start.next=head;        end=head;        int l=1;        for(int i=0;i<n-1;i++){        end=end.next;        l++;        }        while(end.next!=null){        end=end.next;        l++;        start=start.next;        }        //System.out.println(l+","+start.val+","+end.val);        if(l==n)return head.next;        ListNode denode=start.next;        start.next=denode.next;               return head;    }}


0 0
原创粉丝点击