19. Remove Nth Node From End of List
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
又是照着答案都能语法出错的题。。。说明自己的指针都不知道干啥呢~
/**
* 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) {
ListNode* q = head;
ListNode* p = head;
if(head==NULL||head->next==NULL){
return NULL;
}
for(int i=0;i<n;i++){
q=q->next;
}if(q==NULL){
return head->next;
}
q = q->next;
while(q!=NULL){
q=q->next;
p=p->next;
}
p->next = p->next->next;
return head;
}
};
这是榜首的那个人的代码
/**
* 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) {
ListNode *p = head,*q;
q = p;
int i=0,j=0;
while(q != NULL) {
q = q->next;
++i;
}
//cout << i << endl;
while(j<=i-n-1){
++j;
if(j>1) p = p->next;
}
cout << i<<p->val<< j<<endl;
if(j == 0) {
head = head->next;
return head;
} else {
// p->next = NULL
// p->next = p->next->next;
q = p->next;
p->next = q->next;
//free(q);
return (head);
}
}
};