LEETCODE算法入门 链表

删除链表的倒数第 N 个结点

 解析:我的个人思路是,先遍历整个链表找出长度numsSize,然后再找两个指针开始遍历,遍历到target之后进行删除。

代码实现:

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


struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    struct ListNode * count = head;
    //find the numsSize
    int numsSize = 0;
    while(count!=NULL){
        count=count->next;
        numsSize++;
    }
    //subscript is numsSize - n
    int subscript = numsSize - n;
    //reset count and creat a Frontcount
    count = head->next;
    struct ListNode * Frontcount = head;
    //find target
    for(int i=1;i<=subscript-1;i++){
        Frontcount = Frontcount -> next;
        count = count -> next;
    }
    //delete target
    if(numsSize==1)return NULL;
    else if(numsSize==2&&n==2)return count;
    else if(n==numsSize){
        head = count->next;
        free(Frontcount);
        return count;
    }
    Frontcount->next = count->next;
    free(count);
    //reset Frontcount
    Frontcount = head;
    return Frontcount;
}

由于我写的代码出口过多,证明算法过于繁琐

主要问题出现在我的算法

1.只能解决长度不是1或2的链表

2.只能删除FrontNode 和Node 中间的数字,导致如果出现删除第一个数和删除第二个数的时候会发生答案相同的情况。

优化方案:

待编辑

おすすめ

転載: blog.csdn.net/rick030224/article/details/122140197