LeetCode 19. Remove Nth Node From End of List
Solution1:我的答案
并不算是最优解法。
/**
* 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 == NULL || n == 0)
return NULL;
struct ListNode* dummy = new ListNode(-1);
dummy->next = head;
struct ListNode* cur = dummy;
int count = 0;
while (cur->next) {count++; cur = cur->next;}
count = count - n + 1;
cur = dummy;
while (count-- > 1) cur = cur->next;
cur->next = cur->next->next;
return dummy->next;
}
};
Solution2:
参考网址:http://www.cnblogs.com/grandyang/p/4606920.html
其实这是一道经典的链表双指针算法题。
需要用两个指针来帮助我们解题,pre和cur指针。首先cur指针先向前走N步,如果此时cur指向空,说明N为链表的长度,则需要移除的为首元素,那么此时我们返回head->next即可,如果cur存在,我们再继续往下走,此时pre指针也跟着走,直到cur为最后一个元素时停止,此时pre指向要移除元素的前一个元素,我们再修改指针跳过需要移除的元素即可。代码如下:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head->next) return NULL;
ListNode *pre = head, *cur = head;
for (int i = 0; i < n; ++i) cur = cur->next;
if (!cur) return head->next;
while (cur->next) {
cur = cur->next;
pre = pre->next;
}
pre->next = pre->next->next;
return head;
}
};