题意:删除链表中倒数第i个元素。
思路:用堆栈完成计数工作。
/**
* 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) return head;
stack<ListNode*> mys;
ListNode* myhead = new ListNode(0);
ListNode* next = head;
myhead->next = next;
mys.push(myhead);
while(next) {
mys.push(next);
next = next->next;
}
ListNode* after = NULL;
next = mys.top();
mys.pop();
while(n --) {
after = next->next;
next = mys.top();
mys.pop();
}
next->next = after;
return myhead->next;
}
};另一种只遍历一边的做法是,在链表中标记第i个元素到结尾的长度。这样做目的是记录从头到达i-1个元素需要的循环次数。
/**
* 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) {
ListNode* myhead = new ListNode(0);
myhead->next = head;
ListNode* mark = head;
ListNode* next = myhead;
while(n --) {
mark = mark->next;
}
while(mark) {//cout << "here" <<endl;
mark = mark->next;
next = next->next;
}
next->next = next->next->next;
return myhead->next;
}
};
本文介绍两种高效算法来解决链表中倒数第N个节点的删除问题。一种利用堆栈进行计数,另一种仅遍历一次链表,通过标记达到目的。这些方法适用于计算机科学中的数据结构和算法优化。
635

被折叠的 条评论
为什么被折叠?



