国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

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

2023-04-02 15:30 作者:薄荷硬糖醬  | 我要投稿

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

難度中等2492

給你一個鏈表,刪除鏈表的倒數(shù)第?n?個結點,并且返回鏈表的頭結點。

?

示例 1:

輸入:head = [1,2,3,4,5], n = 2輸出:[1,2,3,5]

示例 2:

輸入:head = [1], n = 1輸出:[]

示例 3:

輸入:head = [1,2], n = 1輸出:[1]

?

提示:

  • 鏈表中結點的數(shù)目為?sz

  • 1 <= sz <= 30

  • 0 <= Node.val <= 100

  • 1 <= n <= sz

?

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

第一種法:

/**

?*?Definition?for?singly-linked?list.

?*?struct?ListNode?{

?*?????int?val;

?*?????struct?ListNode?*next;

?*?};

?*/

struct?ListNode*?removeNthFromEnd(struct?ListNode*?head,?int?n){

????struct?ListNode?*newhead?=?(struct?ListNode*)malloc(sizeof(struct?ListNode));

????newhead->next?=?head;

????struct?ListNode?*cur?=?newhead;

????struct?ListNode?*last?=?cur;

????while(1){

????????for(int?i=0;i<n;i++){

????????????last?=?last->next;

????????}

?????????if(last->next==NULL){

????????????struct?ListNode*?tmp?=?cur->next;

????????????cur->next?=?last;

????????????free(tmp);

????????????return?newhead->next;

????????}else{

????????????cur=cur->next;

????????????last?=?cur;

????????}

????}

}

這里的last是只考慮了n是偶數(shù)的情況,當n為奇數(shù)時last將指向需要刪除的元素,與循環(huán)中的代碼矛盾。

第一種法:

/**

?*?Definition?for?singly-linked?list.

?*?struct?ListNode?{

?*?????int?val;

?*?????struct?ListNode?*next;

?*?};

?*/


struct?ListNode*?removeNthFromEnd(struct?ListNode*?head,?int?n){

????struct?ListNode?*newhead?=?(struct?ListNode*)malloc(sizeof(struct?ListNode));

????newhead->next?=?head;

????struct?ListNode?*cur?=?newhead;

????struct?ListNode?*last?=?cur;

????while(1){

????????for(int?i=0;i<=n;i++){

????????????last?=?last->next;

????????}

?????????if(last==NULL){

????????????struct?ListNode*?tmp?=?cur->next;

????????????cur->next?=?cur->next->next;

????????????free(tmp);

????????????return?newhead->next;

????????}else{

????????????cur=cur->next;

????????????last?=?cur;

????????}

????}

}


19. 刪除鏈表的倒數(shù)第 N 個結點的評論 (共 條)

分享到微博請遵守國家法律
柯坪县| 蒙阴县| 和顺县| 宾川县| 滨州市| 淮阳县| 禹州市| 淮滨县| 曲沃县| 唐山市| 宁夏| 东方市| 佛坪县| 巴青县| 盐池县| 西宁市| 三穗县| 五常市| 沙洋县| 巴东县| 徐州市| 尼勒克县| 水富县| 恩施市| 册亨县| 玉环县| 彭水| 江永县| 大庆市| 米林县| 漳州市| 乌鲁木齐市| 吉林省| 长宁县| 宁都县| 子洲县| 沁水县| 封丘县| 承德市| 上栗县| 犍为县|