码迷,mamicode.com
首页 > 其他好文 > 详细

25.Remove Nth Node From End of List(删除链表的倒数第n个节点)

时间:2019-04-26 11:10:31      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:class   note   solution   removing   move   nod   ali   长度   example   

Level:

??Medium

题目描述:

Given a linked list, remove the n-th node from the end of list and return its head.

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.

思路分析:

??题目要求删除链表的倒数第n个节点,首先我们需要判断n是否在有效范围,然后我们计算出链表的长度,求倒数第n个,就是求正数第len-n个。

代码:

public class ListNode{
    int val;
    ListNode next;
    public ListNode(int x ){
        val=x;
    }
}
public class Solution{
    public ListNode removeNthFromEnd(ListNode head,int n){
        if(head==null)
            return null;
        int len=0;
        ListNode pNode=head;
        while(pNode!=null){
            len++;
            pNode=pNode.next;
        }
        if(n>len)
            return null;
        if(len==1&&len==n)
            return null;
        if(len==n)
            return head.next;
        ListNode pNode2=head;
        for(int i=0;i<len-n-1;i++){
            pNode2=pNode2.next;
        }
        pNode2.next=pNode2.next.next;
        return head;
    }
}

25.Remove Nth Node From End of List(删除链表的倒数第n个节点)

标签:class   note   solution   removing   move   nod   ali   长度   example   

原文地址:https://www.cnblogs.com/yjxyy/p/10772910.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!