zoukankan      html  css  js  c++  java
  • LeetCode(19) Remove Nth Node From End of List

    题目

    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,要求删除链表中倒数第n个结点,返回链表头结点。
    题目不难,主要是必须考虑周全;

    • head==NULL || n==0,则直接返回head
    • 链表中结点总数count < n,则直接返回head
    • 链表中结点总数count == n,则head=head->next,返回head
    • 删除中间或尾结点,即删除正序第count-n+1 个结点,将倒序改为正序处理

    AC代码

    /**
     * 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 == NULL || n == 0 )
                return head;
    
            //计算链表中的结点个数
            int count = 0;
            ListNode *p = head;
            while (p)
            {
                count++;
                p = p->next;
            }
    
            //链表中的结点个数小于要删除的倒数第n个
            if (count < n)
            {
                return head;
            }
            else if (count == n)
            {
                ListNode *tem = head;
                head = head->next;
                delete tem;
            }
            else{
                ListNode *p = head, *q = p->next;
                int i = 1;
                while (i < (count - n) && q->next!=NULL)
                {
                    p = p->next;
                    q = q->next;
                    i++;
                }
                p->next = q->next;
                delete q;
            }
            return head;
    
        }
    };

    GitHub测试程序源码

  • 相关阅读:
    opencv ImportError: libSM.so.6: cannot open shared object file: No such file or directory
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcd
    Linux卸载并更新显卡驱动
    人脸识别
    dav转mp4
    python调用c++接口,参数为opencv读取数据
    Linux下内存泄漏工具valgrind
    模型轻量化
    自动驾驶车搭建
    TSN(Temporal Segment Networks)
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214923.html
Copyright © 2011-2022 走看看