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

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;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容