C++ leetcode 19. 刪除鏈表的倒數第N個節點 給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。

一、思路:

     遍歷一遍存儲節點到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;
	}
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章