【C语言刷LeetCode】19. 删除链表的倒数第N个节点(M)

[

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

示例:

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

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

给定的 n 保证是有效的。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

]

又是双指针问题。让一个指针先走即可。

struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    struct ListNode* p1 = head;
    struct ListNode* p2 = head;
    int i;
    int flag = 0;
    
    if (n == 0) {
        return head;
    }
    
    if ((head->next == NULL) && (n ==1)) {
        return NULL;
    }
    
    for (i = 0; i < n; i++) {
        p1 = p1-> next;
    }
    
    if (p1 == NULL) {
        head = head->next;
        return head;
    }
    
    while (p1->next) {
        p1 = p1->next;
        p2 = p2->next;
    }
    
    p2->next = p2->next->next;
    
    return head;
}
发布了102 篇原创文章 · 获赞 17 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/jin615567975/article/details/104290500
今日推荐