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;
        }
    };
    

      

  • 相关阅读:
    部署openstack的官网文档解读mysql的配置文件
    ubuntu14.04行更新软件包
    Ubuntu14.04上修改主机名
    ubuntu上修改root密码
    在ISE查看各个模块消耗的资源
    132
    Aurora 8B/10B、PCIe 2.0、SRIO 2.0三种协议比较
    NAND flash和NOR flash的区别详解
    FPGA三分频,五分频,奇数分频
    以太网之物理层
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3405564.html
Copyright © 2011-2022 走看看