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

2017-08-03  本文已影响0人  jose_dl
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;
    }
}

上一篇下一篇

猜你喜欢

热点阅读