给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
解决思路:先用一指针遍历n+1个结点,然后第二个指针从头开始与这个指针一起遍历,直至第一个指针为空,此时第二个指针为要删除结点的前一个结点。判断是不是头结点然后删除所要删结点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode *head_pre = (struct ListNode *)malloc(sizeof(struct ListNode));
head_pre->next = head;
struct ListNode *p_front = head_pre;
struct ListNode *p_behind = head_pre;
struct ListNode *p_n;
int i;
for (i=0; i<n+1 && p_front; i++)
p_front = p_front->next;
while (p_front)
{
p_front = p_front->next;
p_behind = p_behind->next;
}
p_n = p_behind->next;
if(p_n == head)
{
head = head->next;
return head;
}
if(p_behind && p_n)
p_behind->next = p_n->next;
return head;
}