算法题9:删除链表的倒数第n个节点
思路
与算法题8的思路一致
代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
//if(head == NULL) return NULL;
int count = 0;
ListNode *cur = head;
while(cur!=NULL){ //遍历结点个数
cur = cur->next;
count++;
}
if(count == n){
head = head->next;
}
else{
cur = head;
ListNode *pre = NULL;
for(int i=0; i<count-n; i++){ //找到删除结点
pre = cur;
cur = cur->next;
}
pre->next = pre->next->next; //删除结点
}
return head;
}
};