• 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;
        }
    };
    
  • 相关阅读:
    A1020 Tree Traversals [中序后序建树]
    bfs 找步数最少的迷宫路径
    hdu 1241
    hdu 素数环
    A1054 The Dominant Color [map]
    A1097 Deduplication on a Linked List [链表去重]
    C# 中Dictionary的用法及用途
    C#文件操作
    C# 属性概述
    C# Lock的用法
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6822123.html
Copyright © 2020-2023  润新知