- 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本题采用的就是暴力法:
重点一:求链表长度,暴力遍历
重点二:删除链表的某个节点,head->next = head->next->next
/**
- Definition for singly-linked list.
- struct ListNode {
-
int val;
-
ListNode *next;
-
ListNode(int x) : val(x), next(NULL) {}
- };
/
class Solution {
public:
ListNode removeNthFromEnd(ListNode* head, int n) {
// 链表长度
int lengthNode = 0;
// 为了可以删除头节点,新建一个临时头节点
ListNode* dummy = new ListNode(0);
dummy->next = head;
// 求长度
ListNode* p = head;
while § {
lengthNode++;
p = p->next;
}
// special input
if (lengthNode == 1) {
return NULL;
}
// cout << “l” << lengthNode << endl;
// n肯定有效不需要做有效检查
// 不需要
// n = n % lengthNode;
// for test
// cout << “n” << n << endl;
// 找到要删除节点的位置
int tmp = lengthNode - n + 1;
ListNode* q = dummy;
while (–tmp) {
q = q->next;
}
// if (q->next) {
// q->next = q->next->next;
// } else {
// q->next = NULL;
// }
// 删除节点
q->next = q->next->next;
return dummy->next;
}
};