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-1个数,当前面的指针指向末尾NULL的时候,p刚好指向要删除的那个节点。
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (head==NULL) return NULL; ListNode *p = head; ListNode *q = head; ListNode *pPre = NULL; for(int i=0;i<n-1;i++){ q=q->next; } while(q->next!=NULL){ pPre = p; p=p->next; q=q->next; } if(pPre==NULL) head = p->next; else pPre->next=p->next; delete p; return head; } };
下面的做法是错误的,因为如果删不到第一个结点。所以应该有一个pPre来记录上一个结点的位置。
class Solution { public: ListNode *removeNthFromEnd(ListNode *head, int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (head==NULL) return NULL; ListNode *p = head; ListNode *q = head; for(int i=0;i<n;i++){ q=q->next; } while(q->next!=NULL){ p=p->next; q=q->next; } ListNode *dp=p->next; p->next=p->next->next; delete dp; return head; } };