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-1个数,当前面的指针指向末尾NULL的时候,p刚好指向要删除的那个节点。

    /**
     * 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) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if (head==NULL) return NULL;
            ListNode *p = head;
            ListNode *q = head;
            ListNode *pPre = NULL;
            for(int i=0;i<n-1;i++){
                q=q->next;
            }
            while(q->next!=NULL){
                pPre = p;
                p=p->next;
                q=q->next;
            }
            if(pPre==NULL)
                head = p->next;
            else
                pPre->next=p->next;
            delete p;
            return head;
        }
    };
    

      

    下面的做法是错误的,因为如果删不到第一个结点。所以应该有一个pPre来记录上一个结点的位置。

    class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if (head==NULL) return NULL;
            ListNode *p = head;
            ListNode *q = head;
            for(int i=0;i<n;i++){
                q=q->next;
            }
            while(q->next!=NULL){
                p=p->next;
                q=q->next;
            }
            ListNode *dp=p->next;
            p->next=p->next->next;
            delete dp;
            return head;
        }
    };
    

      

  • 相关阅读:
    Pycharm新建第一个Django项目
    Django的MTV模型
    TCP Retransmission 连接超时
    linux系统参数调优
    企业网站架构
    基于centos7,python3.7新建第一个Django项目
    运维日常错误总结(docker)
    docker常用技巧
    DHCP服务部署
    ssh远程登录故障解决方案
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3405564.html
Copyright © 2011-2022 走看看