一、题目描述
二、思路
- 暴力解法:遍历一遍记录链表长度,然后再遍历一遍找到要删除的节点,删除;
- 涉及到定位,可以使用双指针,因为题目说是删除倒数第N个,所以可以将指针设定为相隔(N )个节点,因此在当走在前头的指针(pre)走到NULL时,走在后头的指针刚好指向将要删除的节点的前一个节点。
- e.g.删除倒数第一个节点👇
三、解题过程
-
定义虚拟头节点
- 因为最后要输出头节点,且头节点有可能给删除掉,所以设置虚拟头节点,以便最后输出头节点:
struct ListNode* pHead = (struct ListNode*)malloc(sizeof(struct ListNode));
pHead -> next = head;
-
定义pre和cur指针
- cur指向虚拟头节点,pre指向与cur相隔N个节点的节点:
struct ListNode* cur = pHead;
struct ListNode* pre = pHead;
for(; n >= 0; n --){
pre = pre -> next;
}
-
移动pre和cur指针
- 移动两个指针,直到pre指针指向NULL,此时cur指向将要删除的节点的前一个节点:
while(pre) {
pre = pre -> next;
cur = cur -> next;
}
-
删除倒数第N个节点
-
定义freeNode,即要删除的节点,同时令cur的next指针指向倒数第(N - 1)个节点,最后释放掉要删除的节点:
struct ListNode* freeNode = cur -> next;
cur -> next = freeNode -> next;
free(freeNode);
-
返回头节点
return pHead -> next;
四、代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* pHead = (struct ListNode*)malloc(sizeof(struct ListNode));
pHead -> next = head;
struct ListNode* cur = pHead;
struct ListNode* pre = pHead;
for(; n >= 0; n --) {
pre = pre -> next;
}
while(pre) {
pre = pre -> next;
cur = cur -> next;
}
struct ListNode* freeNode = cur -> next;
cur -> next = freeNode -> next;
free(freeNode);
return pHead -> next;
}
时间复杂度:O(n),空间复杂度:O(1)