zoukankan      html  css  js  c++  java
  • 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 gap,gap形成以后,以同样的速度移动。当最后一个达到end时,前一个就移动到了从后数的第nth个

    代码:1.如果不添加initialStart的话,就需要检查删除node为head的情况。2.添加初始initialStart的话,所有删除情况一样。

    注意::还有一种简化代码的方法是 [指针的指针]。,我有点晕。。。。下次看

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        /*use two pointer to form a gap*/
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            ListNode *p1,*pn;
            p1=pn=head;
            while(n>=0 && pn){
                pn=pn->next;
                n--;
            }
            // delete the first element from end;
            if(n>=0) {
                head=head->next;
                return head;
            }
            
            while(pn){
                pn=pn->next;
                p1=p1->next;
            }
            if(p1 && p1->next) p1->next=p1->next->next;
            return head;
        }
    };
  • 相关阅读:
    zabbix迁移思路
    top命令
    random随机数
    判断传入元素是否可见
    title_contains
    1.Selenium的工作原理以及网页上查找元素
    APP升级测试
    英语词汇
    作文 |素材笔记
    408计组 |二、数据的表示和运算
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4341065.html
Copyright © 2011-2022 走看看