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

    1. Remove Nth Node From End of List My Submissions QuestionEditorial Solution
      Total Accepted: 106592 Total Submissions: 361392 Difficulty: Easy
      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.
    Submission Details

    207 / 207 test cases passed.
    Status: Accepted
    Runtime: 8 ms

    思路:利用快慢指针,快指针先走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) {
            ListNode *pre=head,*p=head;
            for(int i=0;i<n;++i){  //先向前走n步
                    if(p!=NULL)p=p->next;
                    else return head; 
            }
            if(p==NULL)return head->next; //第n+1个位置为空,那么倒数第n个位置为首元素
            while(p->next){
                   pre = pre->next;   //快慢指针同时走,直到快指针到达最后一个节点
                   p = p->next;
            }
            pre->next = pre->next->next;//删除该节点
            return head;
        }
    };
  • 相关阅读:
    JVM如何执行方法调用
    JVM如何实现反射
    JVM是如何处理异常的
    Java类加载
    windows-Kafka安装
    Google Eventbus简单使用
    队列c#版
    python 元类

    Spring Mvc 笔记二之异常和文件上传
  • 原文地址:https://www.cnblogs.com/freeopen/p/5482924.html
Copyright © 2011-2022 走看看