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.
此题目的在于将一个链表的倒数第n个节点删除。
思路:
1.初始化两个节点p,q,p->next和q->next都指向head;
2.先让p节点往后走n步,然后让p,q节点同时往后走,直到p->next是NULL;
3.此时q->next就是链表的倒数第n个节点,删除这个节点,将链表连接起来;
4返回这个新链表就是最后的结果。
/**
* 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 dummy(-1);
ListNode *p = &dummy;
ListNode *q = &dummy;
dummy.next = head;//p->next和q->next都指向head
while(n--){//p节点往后走n步
p = p->next;
}
while(p->next){//p,q节点同时往后走,直到p->next是NULL
p = p->next;
q = q->next;
}
ListNode *temp = q->next;//q->next就是链表的倒数第n个节点
q->next = q->next->next;//链表连接起来
delete temp;//删除这个节点
return dummy.next;
}
};