remove the nth node

Given a linked list, remove the nth node from the end of list and return its head.
** Notice**
The minimum number of nodes in list is n.

Example
Given linked list: 1->2->3->4->5->null, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5->null.

/**
 * 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
        
        if (head == null) return null;
        
        ListNode p1 = head;
        ListNode p2 = head;
        ListNode prev = null;
        int i = 0;
        
        while (i < n) {
            p1 = p1.next;
            i++;
        }
        
        while (p1 != null) {
            prev = p2;
            p2 = p2.next;
            p1 = p1.next;
        }
        
        if (prev == null) {
            head = head.next;
            return head;
        } 
        
        prev.next = p2.next;
        return head;
        
    }
}

/*

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n <= 0) {
            return null;
        }
        // add one more to the list, then when the while loop ends, get the
        // preDelete node right away
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode preDelete = dummy;
        for (int i = 0; i < n; i++) {
            if (head == null) {
                return null;
            }
            head = head.next;
        }
        while (head != null) {
            head = head.next;
            preDelete = preDelete.next;
        }
        preDelete.next = preDelete.next.next;
        return dummy.next;
    }
}

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

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,864评论 0 23
  • 使用CocoaPods管理第三方框架非常方便,但是有时候也会出现一些问题。 问题来源 今天下载了Coding源码,...
    mieGod阅读 10,151评论 4 11
  • 看了部电影,Once,慢慢的节奏,在开头就被男主嘶吼的倾述所吸引,拽住,想看下去。 如所有电影一般,男主会遇到女主...
    大小囡囡阅读 375评论 0 1
  • 八篇千古家训,存给子孙看 孔子“训子鲤” “不学‘诗’,无以言;不学‘礼’,无以立。” 一日,孔子站在庭院中,他的...
    子正书院阅读 373评论 0 0