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个节点。
思路:
先计算链表节点的个数,然后通过计算找到将要删除的节点删除即可。注意的就是链表为空的情况和删除头节点的情况。
/**
* 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){
return head;
}
int cnt = 0;
ListNode *p = head;
ListNode *q = head;
//计数
while(p != NULL){
++cnt;
p = p->next;
}
//找要删除的节点的前一个节点,方便删除指定节点
for(int i = 0; i < cnt-n-1; ++i){
q = q->next;
}
//如果删除的是首节点的情况
if(n == cnt){
return head->next;
}
ListNode *temp;
temp = q->next;
q->next = temp->next;
free(temp);
return head;
}
};