LeetCode 19. 删除链表的倒数第N个节点

题目链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:

给定的 n 保证是有效的。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
10     struct ListNode *q=head,*pre;
11     int len=0;
12     while(q){
13         len++;
14         q=q->next;
15     }
16     if(n==len) return head->next;
17     len=len-n;
18     q=head;
19     while(len--){
20         pre=q;
21         q=q->next;
22     }
23     q=pre->next;
24     pre->next=q->next;
25     free(q);
26     return head;
27 }
原文地址:https://www.cnblogs.com/shixinzei/p/12402806.html