題目:
給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
說明:給定的 n 保證是有效的。
解題:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* pLst = head;
struct ListNode* nLst = head;
struct ListNode* now = head;
int cnt = 0;
while(now != 0)
{
now = now->next;
if(cnt >= n-1) nLst = nLst->next;
if(cnt >= n+1) pLst = pLst->next;
cnt++;
}
if(cnt == n) return head->next;
pLst->next = nLst;
return head;
}