- Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
题目解析:给定链表,去除链表倒数第n个数,随即想到删除链表中节点,只不过是倒数来删。可把链表放置到stack中,栈得话先进后出,不正好是可解决倒数去除节点得问题。
代码:
/**
* 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)
{
return NULL;
}
stack<ListNode*> s;//初始化堆栈
ListNode* node = head;指向头节点
while(node)//循环,将链表放置到s堆栈中
{
s.push(node);
node = node->next;
}
for(int i=0;i<n;i++)//pop节点至n节点位置
{
s.pop();
}
if(s.empty())//如果n位置节点为空,则返回
{
return head->next;
}
else
{
s.top()->next = s.top()->next->next;//不为空,去掉n位置节点
return head;
}
}
};
性能:
总结:链表去除节点问题,C++比较基础得问题。上周未打卡,深感不安,技术不可一日不琢磨呀,共勉。