C++示例:
/**
* 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) {
if (head == NULL) {
cout << "The list is empty." << endl;
return head;
}
if (head->next == NULL) {
delete head;
return NULL;
}
ListNode* fast = head;
ListNode* slow = head;
for (int i = 0; i < n; i++) {
fast = fast->next;
}
if (fast == NULL) {
ListNode* temp = head->next;
head->val = temp->val;
head->next = temp->next;
delete temp;
return head;
}
while (fast->next != NULL) {
fast = fast->next;
slow = slow->next;
}
ListNode* temp = slow->next;
slow->next = temp->next;
delete temp;
return head;
}
// 两趟扫描实现
/*ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == NULL) {
cout << "The list is empty." << endl;
return NULL;
}
if (head->next == NULL) {
delete head;
return NULL;
}
ListNode* p = head;
int len = 0;
while (p != NULL) {
len++;
p = p->next;
}
p = head;
int pos = len - n + 1;
while (pos > 2) {
pos--;
p = p->next;
}
if (pos == 1) {
ListNode* temp = head->next;
head->val = temp->val;
head->next = temp->next;
delete temp;
return head;
}
ListNode* temp = p->next;
p->next = temp->next;
delete temp;
return head;
}*/
};
原文地址:https://www.cnblogs.com/yiluyisha/p/9266088.html
时间: 2024-11-01 19:29:10