題目描述:
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?
理解:
定義兩個指針,一個在前,一個在后,同時遍歷ListNode,要求是:開始遍歷時fast指針要比slow指針快n步,方法是先讓fast指針先移動n步,然后fast和slow再同時移動,直到移動到末尾。
這里有兩種解決思路,一種直接在ListNode上進行操作,另一種使用一個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; ListNode* new_head = new ListNode(0); new_head->next = head; ListNode* slow = new_head, *fast = new_head; for(int i = 0;i<n;++i){ //fast先移動n fast = fast->next; } if(!fast) return new_head->next; while(fast->next){ //一起移動 fast = fast->next; slow = slow->next; } slow->next = slow->next->next; return new_head->next; } };
解法二:利用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.push(node); node = node->next; } for(int i = 0; i < n; ++i) { s.pop(); } if (s.empty()) { return head->next; } else { s.top()->next = s.top()->next->next; return head; } } };
完