zoukankan      html  css  js  c++  java
  • 【Leetcode】Remove Nth Node From End of List

    题目描述:

    Given a linked list, remove the n-th node from the end of list and return its head.

    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.

    Follow up:

    Could you do this in one pass?

    理解:

      定义两个指针,一个在前,一个在后,同时遍历ListNode,要求是:开始遍历时fast指针要比slow指针快n步,方法是先让fast指针先移动n步,然后fast和slow再同时移动,直到移动到末尾。

    这里有两种解决思路,一种直接在ListNode上进行操作,另一种使用一个stack。

    解法一:

    /**
     * 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) {
            if(!head) return NULL;
            ListNode* new_head = new ListNode(0);
            new_head->next = head;
            ListNode* slow = new_head, *fast = new_head;
            for(int i = 0;i<n;++i){  //fast先移动n
                fast = fast->next;
            }
            if(!fast) return new_head->next;
            while(fast->next){      //一起移动
                fast = fast->next;
                slow = slow->next;
            }
            slow->next = slow->next->next;
            return new_head->next;
        }
    };

    解法二:利用stack来解决

    /**
     * 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) {
            if(!head) return NULL;
            stack<ListNode*> s;
            ListNode* node = head;
           while(node){
               s.push(node);
               node = node->next;
           }
            for(int i = 0; i < n; ++i) {
                s.pop();
            }
           if (s.empty()) {
                return head->next;
            } else {
                s.top()->next = s.top()->next->next;
                return head;
            }
        }
    };

  • 相关阅读:
    【代码笔记】iOS-判断textField里面是否有空
    【代码笔记】iOS-判断字符串是否为空
    【代码笔记】iOS-判断中英文混合的字符长度的两种方法
    【代码笔记】iOS-判断有无网络
    【代码笔记】iOS-判断是否是iPhone5
    iOS动画-扩散波纹效果
    (转)对称加密与非对称加密,以及RSA的原理
    (转)iOS GPUImage研究总结
    @inerface的11条规范写法
    Python开发之路
  • 原文地址:https://www.cnblogs.com/ygh1229/p/9679510.html
Copyright © 2011-2022 走看看