leetcode 19. 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.
思路:
最直接的思路,应该是先统计链表节点的个数num,然后再找到第num-n-1那个节点x,把那个x节点的next指向x->next->next就行了。但是这个很明显不能在一遍遍历解决。
可以用双指针的思想初始p=head q=head。开始走n个节点到p,然后从p->next开始,和q一起走,知道p->next为nullptr,那么此时的q就是上个思路的x节点。那么q->next=q->next->next就行了。
代码如下:
* 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) {
if(head == NULL || head->next == NULL)
return NULL;
ListNode *p = head;
ListNode *q = head;
while(--n >= 0) p = p->next;
if(p == NULL) return head->next;
p = p->next;
while(p != NULL) {
p = p->next;
q = q->next;
}
q->next = q->next->next;
return head;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: