leetcode Remove Nth Node From End of List
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.
PS:大早上遇到一道简单题还是非常令人开心的。
非常简单,首先遍历得到length。然后遍历至length-n(也就是要删除的节点)删除就行了。
注意两个地方,假如删除的是头节点,也就是length==n的时候,还有就是假如删除的是尾节点,最后就是最普通的删除的是中间节点。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeNthFromEnd(ListNode* head, int n) { 12 int length=0; 13 ListNode* p=head,*q; 14 while(p!=NULL){ 15 p=p->next; 16 length++; 17 } 18 if(length==n){ 19 if(head->next!=NULL) { 20 head=head->next; 21 return head;} 22 else return NULL; 23 } 24 p=head; 25 q=p; 26 for(int i=0;i<length-n;i++){ 27 q=p; 28 p=p->next; 29 } 30 if(p->next!=NULL) q->next=p->next; 31 else q->next=NULL; 32 return head; 33 } 34 };