[LeetCode]19.Remove Nth Node From End of List
【題目】
Given a linked list, remove the nth node from the end of list and return its head.
For 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.
Try to do this in one pass.
【題意】
給你一個鏈表,去除掉倒數第n個節點。
【分析】
設兩個指針 p; q,讓 q 先走 n 步,然後 p 和 q 一起走,直到 q 走到尾節點,刪除 p->next 即可。
【代碼】
/********************************* * 日期:2014-01-29 * 作者:SJF0115 * 題號: Remove Nth Node From End of List * 來源:https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ * 結果:AC * 來源:LeetCode * 總結: **********************************/ #include <iostream> #include <stdio.h> #include <algorithm> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { if (head == NULL || n <= 0){ return head; } ListNode *dummy = (ListNode*)malloc(sizeof(ListNode)); dummy->next = head; ListNode *temp = NULL; ListNode *pre = dummy,*cur = dummy; //cur先走N步 for(int i = 0;i < n;i++){ cur = cur->next; } //同步前進直到cur到最後一個節點 while(cur->next != NULL){ pre = pre->next; cur = cur->next; } //刪除pre->next temp = pre->next; pre->next = temp->next; delete temp; return dummy->next; } }; int main() { Solution solution; int A[] = {1,2,3,4,5}; ListNode *head = (ListNode*)malloc(sizeof(ListNode)); head->next = NULL; ListNode *node; ListNode *pre = head; for(int i = 0;i < 5;i++){ node = (ListNode*)malloc(sizeof(ListNode)); node->val = A[i]; node->next = NULL; pre->next = node; pre = node; } head = solution.removeNthFromEnd(head->next,4); while(head != NULL){ printf("%d ",head->val); head = head->next; } return 0; }
最後更新:2017-04-03 12:54:51