同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
题目为给定一个链表 ( Linked List ) 与一个数字 n ,n 代表要移除从后面数来第几个节点。
题目与范例如下
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.