美文网首页
lintcode 166 删除链表倒数第n个数

lintcode 166 删除链表倒数第n个数

作者: jose_dl | 来源:发表于2017-08-03 21:31 被阅读0次
    image.png
    /**
     * Definition for ListNode.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int val) {
     *         this.val = val;
     *         this.next = null;
     *     }
     * }
     */
    public class Solution {
        /**
         * @param head: The first node of linked list.
         * @param n: An integer.
         * @return: The head of linked list.
         */
        ListNode removeNthFromEnd(ListNode head, int n) {
            // write your code here
        //count size of list
            if(n == 0 && head ==null){
                return null;
            }
            if(n == 0){
                return head;
            }
            //compute list length
            int len = 0;
            ListNode node = head;
            while(node != null){
                len++;
                node = node.next;
            }
        //n==len,删除head
            if (n==len){
                return head.next;
            }    
        //len>n
            int count = 1;
            ListNode node1 = head;
            while (count != len-n){
                node1 = node1.next;
                count++;
            }
            node1.next = node1.next.next;
            return head;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:lintcode 166 删除链表倒数第n个数

          本文链接:https://www.haomeiwen.com/subject/zrrmlxtx.html