最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

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

分享到微博請遵守國家法律
彭阳县| 池州市| 巴林左旗| 黑龙江省| 利津县| 陆川县| 揭西县| 嘉祥县| 象州县| 石门县| 开原市| 林口县| 旌德县| 潜山县| 嵊泗县| 象山县| 肇东市| 泰来县| 辽宁省| 定州市| 阿拉尔市| 吉木萨尔县| 满城县| 寿阳县| 山西省| 台中县| 息烽县| 丰镇市| 拜城县| 临桂县| 循化| 东方市| 龙井市| 石柱| 云南省| 新乐市| 郎溪县| 同江市| 乐平市| 宝山区| 腾冲县|