[TOC]
思路
- 知道链表的长度
- 确定要删除的节点的位置
- 处理特殊情况:
- 只有一个元素
- n == count
解题方法
由思路可知
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
struct ListNode *p = head, *q;
int count = 0;
while(p) {
p = p->next;
count++;
}
q = p = head;
int postion = 0;
while(postion < count-n-1 && p->next) {
p = p->next;
postion++;
}
if(postion == count-n-1) {
q = p->next;
p->next = p->next->next;
} else if(n == count) {
q = head;
head = p->next;
}
free(q);
return head;
}