• 19. Remove Nth Node From End of List 删除倒数第n各节点


    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.

    删除倒数第n个节点,主要有两种做法

    法一:先遍历得到链表的长度length,倒数第n个就是正数第length-n+1个(如1 2 3,倒数第三个节点就是3-3+1=1,即第一个节点)

    /**
     * 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) {
            ListNode* newlist= new ListNode(0);
            newlist->next = head;  //带头节点的链表
            int length = 0;
            ListNode* first = head;
            while(first != NULL){   //得到链表长度
                length++;
                first = first->next;
            }
            if(n > length) return NULL;
            int n1 = length + 1 - n;//倒数第n个是在正数第n1个节点
            first = newlist; 
            while(n1 - 1 > 0){         //找到目标节点的前一个位置,便于删除目标节点
                n1--;
                first = first->next;
            }
            first->next = first->next->next;  //删除目标节点
            return newlist->next;  //返回不带头节点的链表
        }
    };

    法二:利用两个指针,快指针先走,找到第n个节点,再启动慢指针。

                        此时快慢指针相距n,让两个指针一起走,快指针走到尾节点时,慢指针刚好到倒数第n个节点。

    /**
     * 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 nullptr;
    
            ListNode new_head(-1);
            new_head.next = head;
    
            ListNode *slow = &new_head, *fast = &new_head;
    
            for (int i = 0; i < n; i++)  //快指针先走到第n个节点
                fast = fast->next;
    
            while (fast->next)   //快慢指针一起走
            {
                fast = fast->next;
                slow = slow->next;
            }
    
            ListNode *to_do_deleted = slow->next;   //这两行负责删除操作
            slow->next = slow->next->next;
    
            delete to_do_deleted;
    
            return new_head.next;
        }
    };
  • 相关阅读:
    MSIL实用指南-一维数组的操作
    MSIL实用指南-给字段、属性、方法、类、程序集加Attribute
    MSIL实用指南-比较运算
    MSIL实用指南-逻辑运算
    MSIL实用指南-位运算
    MSIL实用指南-数学运算
    MSIL实用指南-创建对象
    MSIL实用指南-装箱拆箱
    MSIL实用指南-生成构造函数
    K8S从入门到放弃系列-(5)kubernetes集群之kube-apiserver部署
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7816160.html
Copyright © 2020-2023  润新知