zoukankan      html  css  js  c++  java
  • leetcode--Remove Nth Node From End of List

    1.题目分析

    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.

    2.解法分析

    对于链表的题,双指针法经常用到,这个题目就可以设置两个指针,题意说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) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(n<=0)return head;
            if(head==NULL)return NULL;
            
            ListNode *forward=head;
            
            
            int margin=0;
            while(margin<n&&forward!=NULL)
            {
                margin++;
                forward=forward->next;
            }
            
            if(margin<n)return head;
            
            ListNode *afterward=head;
            ListNode *prev=head;
            while(forward!=NULL)
            {
                prev=afterward;
                afterward=afterward->next;
                forward=forward->next;
            }
            
            if(afterward==head)
            {
                prev=head;
                afterward=head->next;
                free(head);
                return afterward;
            }
            
            prev->next=afterward->next;
            free(afterward);
            return head;
            
            
        }
    };
  • 相关阅读:
    【java】详解java多线程
    【java】switch case支持的6种数据类型
    【Java】详解java对象的序列化
    【java】详解I/O流
    【java】自定义异常类
    【java】详解集合
    【NotePade++】NotePade++如何直接编译运行java文件
    【java】JVM的内存区域划分
    Unicode和UTF的关系
    【java】解析java中的数组
  • 原文地址:https://www.cnblogs.com/obama/p/3275286.html
Copyright © 2011-2022 走看看