五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網(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 個結點的評論 (共 條)

分享到微博請遵守國家法律
交城县| 清水县| 西峡县| 泸定县| 日照市| 五河县| 犍为县| 九江县| 遵化市| 白河县| 徐闻县| 武汉市| 镇宁| 修武县| 左权县| 桐梓县| 诸城市| 延庆县| 丘北县| 静安区| 弥勒县| 腾冲县| 乾安县| 什邡市| 鞍山市| 中江县| 双牌县| 塔城市| 五大连池市| 科尔| 黄山市| 宣威市| 高邑县| 闽清县| 电白县| 贵溪市| 大埔县| 旺苍县| 蒙阴县| 黄梅县| 腾冲县|