题目难度: Medium
原题描述:
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个结点,尽量只遍历一次链表。
解题思路:
这道题是面试的经典题,一般是要你返回这个结点,只不过这题要你删除而已。解题的思路是设置三个指针,让第一个指针先走到第n个结点,然后第二个指针和第一个指针一起走,第三个指针指向第二个指针的前一个结点,直到第一个指针走到最后一个结点为止,此时第二个指针指向的结点为倒数第n个结点。
虽然题目说了给出的n保证有效,但是我还是加了n小于整条链表的长度时的情况的判断,这点很重要,能保证程序的鲁棒性。另外如果链表的长度刚好是n时,此时删除的是头结点,不能使用第三个指针,并且头指针要移到下一个结点中。
时间复杂度分析:
扫描一遍链表的时间复杂度为O(n),n为链表的长度,删除结点操作为常数时间,可以忽略。因此总的时间复杂度为O(n)。
以下是代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
struct ListNode* p1;
struct ListNode* p2;
struct ListNode* p3;
p1 = p2 = head;
p3 = NULL;
for(int i=1 ; i<=n-1 && p1 ; ++i){
p1 = p1->next;
}
if(!p1){
return head;
}
while(p1->next){
p1 = p1->next;
p3 = p2;
p2 = p2->next;
}
if(!p3){
head = p2->next;
free(p2);
}else if(p3 && p2){
p3->next = p2->next;
free(p2);
}
return head;
}