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

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

分享到微博請遵守國家法律
尤溪县| 延寿县| 闵行区| 进贤县| 镇雄县| 喀什市| 贵州省| 南木林县| 开原市| 娱乐| 临安市| 祁东县| 清水县| 平凉市| 乌拉特中旗| 会同县| 贵州省| 邮箱| 浦北县| 东光县| 嘉鱼县| 阿克陶县| 柘荣县| 阜宁县| 麦盖提县| 惠州市| 成安县| 璧山县| 日喀则市| 波密县| 武宁县| 普兰店市| 绥宁县| 威宁| 灵璧县| 青冈县| 马龙县| 静安区| 黑水县| 敖汉旗| 永吉县|