leetcode019(鏈表) 刪除鏈表的倒數(shù)第N個節(jié)點

19. 刪除鏈表的倒數(shù)第N個節(jié)點

難度中等

給定一個鏈表,刪除鏈表的倒數(shù)第 *n *個節(jié)點,并且返回鏈表的頭結(jié)點。

示例:

給定一個鏈表: 1->2->3->4->5, 和 n = 2.

當(dāng)刪除了倒數(shù)第二個節(jié)點后,鏈表變?yōu)?1->2->3->5.

說明:

給定的 n 保證是有效的。

進階:

你能嘗試使用一趟掃描實現(xiàn)嗎?

注意:題目的測試用例是沒有空的頭節(jié)點的,head直接指向第一個節(jié)點

My solution

public class Solution {
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null)
            return head;
        ListNode cur=head;
        int num=0;
        for(;cur!=null;num++){
            cur=cur.next;
        }
        if(num==n)
            return head.next;
        cur=head;
        for(int i=1;i<num-n;i++){
            cur=cur.next;
        }
        cur.next=cur.next.next;
        return head;
    }
}

我并沒有實現(xiàn)遍歷一遍的要求

快慢指針

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {    
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode start = pre, end = pre;
        while(n != 0) {
            start = start.next;
            n--;
        }
        while(start.next != null) {
            start = start.next;
            end = end.next;
        }
        end.next = end.next.next;
        return pre.next;
    }
}

作者:guanpengchn
鏈接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/hua-jie-suan-fa-19-shan-chu-lian-biao-de-dao-shu-d/

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容