首页 > 代码库 > [LeetCode]Remove Nth Node From End of List

[LeetCode]Remove Nth Node From End of List

提米:删除链表从尾部到头部第N的节点。

思路:

两个指针,一个从头开始前移N个节点后,第二个指针开始移动,当第一指针移动到末尾时,第二个指针指向的是从尾部到头部的第N个节点。

注意:

1.N不合法,大于链表长度

2.要删除的是头结点

/*****************************************************************************************
Given a linked list, remove the nth node from the end of list and return its head.
For example,
   Given linked list: 1->2->3->4->5, and n = 2.
   After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
*****************************************************************************************/
#include<stdio.h>

struct ListNode {
    int val;
    struct ListNode *next;
};

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        if(n <= 0)return head;
        struct ListNode *p = head;
    for(;n > 0 && p!= NULL;n--)p = p->next;
    
    if(n > 0)return head;//n过大,比链表的实际长度大
    if(p == NULL){//要删除的是头结点
        p = head;
        head = head->next;
        free(p);
        return head;
    }

    struct ListNode *f = head;//第二个指针
    while(p->next != NULL){//两个指针一起移动
        p = p->next;
        f = f->next;
    }
    p = f->next;
    f->next = p->next;
    free(p);
    return head;
}

void main(){
    int k = 5;
    struct ListNode *l = (struct ListNode *)malloc(sizeof(struct ListNode));
    l->val = k;
    l->next = NULL;
    while(k--){
        struct ListNode *p = (struct ListNode *)malloc(sizeof(struct ListNode));
        p->val = k;
        p->next = l;
        l = p;
    }

    struct ListNode *r = l;
    while(r != NULL){
        printf("%d ",r->val);
        r = r->next;
    }
    printf("\n");

    r = removeNthFromEnd(l,3);
    
    while(r != NULL){
        printf("%d ",r->val);
        l = r;
        r = r->next;
        free(l);
    }
}

 

[LeetCode]Remove Nth Node From End of List