文章目录
List
tips:
增加头节点可以使结构更清晰,时间复杂度:O(N),空间复杂度:O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
/** * 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* dummy = new ListNode(0); dummy->next = head; ListNode* fast = dummy; ListNode* normal = dummy; for(int i = 0; i < n; ++i) { fast = fast->next; } while(fast->next != NULL) { fast = fast->next; normal = normal->next; } ListNode *tmp = normal->next; normal->next = normal->next->next; delete(tmp); return dummy->next; } };
|
近期评论