一、思路:
遍歷一遍存儲節點到vector數組中,然後利用數組指向倒數第n個,將倒數n-1的節點的next指向倒數n的next
二、代碼:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
vector<ListNode*>nodeLists;
ListNode *nowNode = head;
while (nowNode != NULL) {
nodeLists.push_back(nowNode);
nowNode = nowNode->next;
}
int index = nodeLists.size() - n;
if (index <= 0)
return head->next;
nodeLists[index - 1]->next = nodeLists[index]->next;
delete nodeLists[index];
return head;
}
};