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

  • 相关阅读:
    Ubuntu 15.04 下apt-get安装JDK
    Ubuntu下apt-get安装Java,Tomcat
    虚拟化技术比较 PV HVM
    Java8 Lambda表达式教程
    SpringMVC实现上传和下载
    web.xml中的url-pattern映射规则
    java文件读写操作大全
    Java创建文件
    JAVA文件中获取路径及WEB应用程序获取路径方法
    session.flush()与session.clear()的区别及使用环境
  • 原文地址:https://www.cnblogs.com/ygh1229/p/9679510.html
Copyright © 2020-2023  润新知