首页 > 代码库 > [LeetCode]Remove Nth Node From End of List

[LeetCode]Remove Nth Node From End of List

Q: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个结点。如果没有条件限制,可以先一次遍历该链表求出链表的长度,然后再遍历定位到第len-n个结点,删除;但是这里要求只能遍历一次,所以使用两个指针pre和post,post-pre=n-1。二者同时后移,当post到达最后一个结点时,pre所指的结点就是要删除的结点。

思路很简单,但是容易出错,要考虑多个边界问题:

1. 链表为空,直接返回

2. 链表的长度小于n

为了方便,增加一个头结点,指向head。一开始没有使用头结点,在len <= n 的情况下出错,因为删除无头结点的链表的头结点和中间结点,处理方式是不同的;为了统一,加上头结点。

下面贴上代码:

class Solution {
public:
	ListNode *removeNthFromEnd(ListNode *head, int n) {
		ListNode* temp = new ListNode(0);
		temp->next = head;
		if (head != NULL){
			ListNode* pre = head;
			ListNode* post = head;
			ListNode* prepre = temp;
			for (int i = 0; i < n-1; i++){
				post = post->next;
				if (post == NULL)
					break;
			}
			if(post != NULL){
				while (post->next != NULL){
					post = post->next;
					pre = pre->next;
					prepre = prepre->next;
				}
				ListNode* node = prepre->next;
				prepre->next = node->next;
				delete node;
			}
		}
		return temp->next;
	}
};


[LeetCode]Remove Nth Node From End of List