LeetCode (力扣) 19. Remove Nth Node From End of List (C) - Medium

同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。

题目为给定一个链表 ( Linked List ) 与一个数字 n ,n 代表要移除从后面数来第几个节点。

 

题目与范例如下

這張圖片的 alt 屬性值為空,它的檔案名稱為 remove_ex1.jpg

 

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2:

Input: head = [1], n = 1
Output: []
Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

Follow up: Could you do this in one pass?


 

解题策略为透过三个指针,第一个为遍历整个链表( Link List ) 用的,第二个指针为与第一个指针差n ,用以指出倒数第n 个节点,第三个指针为第二个指针后面一个,用以移除第n 个节点用。

 

下方为我的代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    struct ListNode* first = head;
    struct ListNode* second = head;
    struct ListNode* secondback = head;
    for(int i = 0;i<n;i++){
        first = first->next;
    }
    while(first!=NULL){
        if(second == secondback){
        }
        else{
            secondback = secondback->next;
        }
        first = first->next;
        second = second->next;
    }
    if(second == head)
        head = second->next;
    else
        secondback->next = second->next;
    
    return head;
}

 

下方为时间与空间之消耗

Runtime: 0 ms, faster than 100% of C online submissions for Remove Nth Node From End of List.

Memory Usage: 5.8 MB, less than 81.55% of C online submissions for Remove Nth Node From End of List.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值