1. 程式人生 > >LeetCode 19. Remove Nth Node From End of List(刪除單鏈表倒數第N個結點)

LeetCode 19. Remove Nth Node From End of List(刪除單鏈表倒數第N個結點)

題目描述:

    Given a linked list, remove the nth node from the end of list and return its head.

例子:

   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.

分析:
    題意:給定一個單鏈表,移除它的倒數第n個結點並返回。

LeetCode 19

    思路:為了方便操作,我們用指標h建立一個空結點(方便指標

pre的操作,同時也為了應對“刪除第一個結點”這種情況),使其next指標指向指標head。初始化指標pre指向指標h,指標p和q指向指標head,接下來分三步:①指標q向前移動(n-1)步;②指標pre、p、q同時向前移動,直到指標q到達尾結點;③修改指標pre指向結點的next指標指向指標p指向結點的next指標指向的結點,並刪除指標p指向的結點,最後返回指標h指向結點的next指標。

程式碼:

#include <bits/stdc++.h>

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) {
		// Exceptional Case: 
		if(!head){
			return head;
		}
        ListNode* h = new ListNode(-1), *pre = h, *p = head, *q = head;
		h->next = head;
		for(int i = 1; i <= n - 1; i++){
			q = q->next;
		}
		while(q->next){
			q = q->next;
			pre = pre->next;
			p = p->next;
		}
		pre->next = p->next;
		delete(p);
		return h->next;
    }
};