day9

[0019.删除链表的倒数第N个节点]

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *shead = new ListNode ();
        shead->next = head;
        ListNode *pre = shead;
        ListNode *cur = shead;
        int count=0;
        while (cur->next !=nullptr){
            cur = cur->next;
            count++;
        }
        if (count == 1){
            shead->next = nullptr;
        }
        else{
            cur = shead;
            for (int i = 0; i <= (count - n ); i++){
                pre = cur;
                cur = cur->next;
            }
            pre->next = cur->next;
            delete cur;
        }
        return shead->next; 
    }
};
  • 运行成功。其实还是调试了一下,因为没考虑到数组中只有一个元素的情况,所以加了个if else判断。思路就是先把链表从头到尾遍历一遍用count记录节点总个数,然后就是把倒数第n个转化为正数第几个下标算出来,再来一次遍历进行删除操作。我感觉卡哥应该有更简单的思路 去看看
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *shead = new ListNode ();
        shead->next = head;
        ListNode *slow = shead;
        ListNode *fast = shead;
        for (int i = 0; i < n; i++){
            fast = fast->next;
        }
        //fast = shead;
        while(fast->next != nullptr){
            slow = slow->next;
            fast = fast->next;
        }
        ListNode *temp = slow->next; 
        slow->next = slow->next->next;
        delete temp;
        return shead->next;
    }
};
  • 看了卡哥思路 写了代码 开始调试不通过 上面那句注释掉就可以了 因为fast不是跟slow一起从头开始的 不然费那么大功夫在开头只移动fast不移动slow是干嘛 就是为了和slow拉开相应差距啊~ 我那一句直接让fast一下回到解放前了>-<

  • 今天这两段代码每段用了将近40min 还是慢 不过比前两天进步多了 慢慢来 不着急

  • 卡哥代码里有些语句我还要再学学 自己是写不出来的

    while(n-- && fast != NULL) {
         fast = fast->next; 
     }
    

    注意:先判(n且fast 不是空)这个条件为真----进入while---n再--; 疑问:while中的n是减之前的数还是减了之后的数? 我认为是减了之后的数 因为n--是先判断后运算 那么相必进入while之前 也就是在判断之后已经运算过了 到时候输出一下就行了 <<<<<cout了 以上想法完全正确!!
    明天继续:)

posted @ 2022-11-03 22:01  跬步瑶  阅读(23)  评论(0)    收藏  举报