• LeetCode: Remove Nth Node From End of List


    Title:

    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.


    思路: 先让一个指针走n步,在让另一个指针一起向前。需要注意n的取值。有可能直接删除头指针,需要判断

    
    

    class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            if(head == NULL){
                return head;
            }
            ListNode* dummy = new ListNode(0); // 处理删除头指针
            dummy->next = head;
            head = dummy;
            ListNode* slow = head;
            ListNode* fast = head;
            for(int i = 0; i <n; i++){
                fast = fast ->next;
            }
            while(fast->next != NULL){
                fast = fast->next;
                slow = slow->next;
            }
            ListNode* temp = slow->next;
            slow ->next = slow->next->next;
            delete temp;
            return dummy->next;
        }
    };

     
  • 相关阅读:
    215. 数组中的第K个最大元素
    c++集合的操作
    201. 数字范围按位与
    150. 逆波兰表达式求值
    二叉树的遍历算法
    144. 二叉树的前序遍历
    139. 单词拆分 DP
    131. 分割回文串
    695. 岛屿的最大面积 DFS
    leetcode 200. 岛屿数量 DFS
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4421307.html
Copyright © 2020-2023  润新知