LeetCode:19. Remove Nth Node From End of List删除链表的倒数第N个节点(C语言)

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

示例:

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

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

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn2925/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解答:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
   if (!head || !head->next) return NULL;

    int i = 0;

    struct ListNode* pre = NULL;
    struct ListNode* last = NULL;

    pre = head;
    last = head;

    for(int i=0;i<n;i++)
    {
        if(last->next)
            last=last->next;//若last->next不为空则将指针向后推
        else
            return head->next;
    }

    while(last->next){
        last = last->next;
        pre = pre->next;
    }

    pre->next=pre->next->next;

    return head;
}

运行结果:
在这里插入图片描述

你可能感兴趣的:(LeetCode)