zoukankan      html  css  js  c++  java
  • [LeetCode]78. Remove Nth Node From end of List删除链表中倒数第N个节点

    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.

    Subscribe to see which companies asked this question

    解法1:首先扫描一遍链表,统计共有多少个元素;然后从头开始遍历链表,直到到达要删除节点的前一个节点。因为题目限定了输入n总是有效的,所以不需要考虑n大于链表长度或者n小于等于0这些情况。

    /**
     * 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 == NULL) return NULL;
            ListNode* p = head;
            int num = 0;
            while(p != NULL) {
                ++num;
                p = p->next;
            }
            if(num - n == 0) { // 删除的是头节点
                ListNode* del = head;
                head = head->next;
                delete del;
            }
            else {
                p = head;
                for(int i = 0; i < num - n - 1; ++i)
                    p = p->next;
                ListNode* del = p->next;
                p->next = p->next->next;
                delete del;
            }
            return head;
        }
    };

    解法2:一趟遍历解决问题。因为删除某个节点需要改动其前一个节点的next指针,因此我们先找到要删除节点的前一个节点。设置快慢两个指针,初始时都指向头节点。在快指针向前移动N步之后(注意,若此时快指针到达了链表的尾部,即为NULL,则说明删除的是头节点,需要单独考虑),两个指针同时向后移动,直到快指针是尾节点。

    /**
     * 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 == NULL) return NULL;
            ListNode* p1 = head;
            ListNode* p2 = head;
            for(int i = 0; i < n; ++i)
                p1 = p1->next;
            if(p1 == NULL) { //删除的是头节点
                ListNode* del = head;
                head = head->next;
                delete del;
                return head;
            }
            while(p1->next != NULL) {
                p1 = p1->next;
                p2 = p2->next;
            }
            ListNode* del = p2->next;
            p2->next = p2->next->next;
            delete del;
            return head;
        }
    };
  • 相关阅读:
    Xcode代码块快捷输入
    Git常用命令
    vim
    MACOX中apache配置
    IOS中实现动画的几种方式
    Swift与OC混合编译
    网络图像加载
    我对互联网的理解
    运行时
    自动布局使用
  • 原文地址:https://www.cnblogs.com/aprilcheny/p/4963232.html
Copyright © 2011-2022 走看看