[LeetCode_19] Remove Nth Node From End of List_删除链表的倒数第N个节点

leetcode_19


题目描述:

Given a linked list, remove the n-th node from the end of list and return its head.

Example:
Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes1->2->3->5.


思路:

​ 定义两个指针,一个叫做slow,一个叫做 fast,fast就是跑在前面的,slow就是跑在后面的。你要找倒数第n(n是合理的输入,不会超过链表长度)个,那我先让fast从链表头往前跑n步,当fast站在第n个节点这个位置的时候,slow开始从起点跑,fast也同步从n跑,当fast到终点的时候,slow所在位置的下一个节点就是倒数第n个节点了。

[LeetCode_19] Remove Nth Node From End of List_删除链表的倒数第N个节点

代码:

方法1:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode ret, *p = &ret, *q = head;
    ret.next = head;
    while(n--) {
        q = q -> next;
    }
    while(q) {
        p = p->next;
        q = q->next;
    }
    q = p->next;
    p->next = q->next;
    free(q);
    return ret.next;
}
方法2:
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    int len = 0;
    struct ListNode ret, *p = head, *q;
    ret.next = head;
    while(p) {
        p = p->next;
        len++;
    }
    p = &ret;
    len -= n;
    while(len--) {
        p = p->next;
    }
    q = p->next;
    p->next = q->next;
    free(q);
    return ret.next;
}