ListNode* removeNthFromEnd(ListNode* head, int n){ ListNode* dummy = newListNode(0, head); ListNode* first = head; ListNode* second = dummy; for (int i = 0; i < n; ++i) { first = first->next; } while (first) { first = first->next; second = second->next; } second->next = second->next->next; ListNode* ans = dummy->next; delete dummy; return ans; }
注意:用到node->next 一定要保证node不为空结点,避免为空的一个好方法是使用哨兵结点。
stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
ListNode* removeNthFromEnd(ListNode* head, int n){ ListNode* work = head; ListNode* dummy = newListNode(0, head); std::stack<ListNode*> stack; stack.push(dummy); while (work) { stack.push(work); work = work->next; } for (int i = 0; i < n; ++i) { stack.pop(); } stack.top()->next = stack.top()->next->next; ListNode* res = dummy->next; delete dummy; return res; }