• Leetcode: 19. Remove Nth Node From End of List


    Description

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

    Example

    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.
    

    思路

    • 边界情况主要最第一个和最后一个的处理
    • 先遍历链表,找出链表长度
    • 然后计算出要删除的节点的前一个节点
    • 此时,需要分清楚是否是删除第一个节点。然后就没有然后了

    代码

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            if(!head) return NULL;
            
            ListNode *ptr = head;
            int len = 0;
            
            while(ptr){
                ptr = ptr->next;
                len++;
            }
    
            ptr = head;
            int tmp = len - n;
            n = tmp;
            cout << tmp << endl;
            while(tmp > 1){
                ptr = ptr->next;
                tmp--;
            }      
            
            if(n > 0){
                if(ptr->next){
                    ListNode *tmp = ptr->next;
                    ptr->next = tmp->next;
                    delete tmp;
                }
                else ptr->next = NULL;
            }
            else
            {
                ListNode *tmp = head;
                head = head->next;
                delete tmp;
            }
            
            return head;
        }
    };
    
  • 相关阅读:
    bzoj2006[NOI2010]超级钢琴
    bzoj1088[SCOI2005]扫雷
    bzoj1207[HNOI2004]打鼹鼠
    bzoj2132圈地计划
    bzoj2127happiness
    bzoj1037[ZJOI2008]生日聚会
    bzoj1031[JSOI2007]字符加密
    bzoj1566[noi2009]管道取珠
    bzoj2134单选错位
    vuejs之v-on小例子之实现购买数量的增加和减少
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6822123.html
Copyright © 2020-2023  润新知