LeetCode: Remove Nth Node From End of List

题目

https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

分析

  1. 两个指针, 第一个指针先走n步, 然后两个指针一起走, 直到第一个指针走到结尾处, 此时第二个指针即为要删除的结点的上一个结点。

  2. 特别要注意的一点是, 如果要删除的结点是第一个结点, 要特别的处理一下, 因为第二个指针无法指向第一个结点的上一个结点。

代码

class Solution
{
public:
	ListNode *removeNthFromEnd(ListNode *head, int n)
	{
		ListNode *l, *r;

		l = head;
		r = head;
		for (int i = 0; i < n; i++)
			r = r->next;

		if (r == NULL)
		{
			ListNode *t = head;
			head = head->next;
			delete t;
		}
		else
		{
			while (r->next != NULL)
			{
				l = l->next;
				r = r->next;
			}
			ListNode *t = l->next;
			l->next = t->next;
			delete(t);
		}
		return head;
	}
};

本文章迁移自http://blog.csdn.net/timberwolf_2012/article/details/39289759

/** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://chenzz.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })();