zoukankan      html  css  js  c++  java
  • (链表 双指针) leetcode 19. 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?

    -------------------------------------------------------------------------------------------------------------------------

    这个题就是移去从表尾开始的第n 个元素。emmmm,这个最好画图,便于理解。

    可以用双指针。

    C++代码:

    /**
     * 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) {
            ListNode *s = head;
            ListNode *e = head;
            if(!head) return NULL;
            for(int i = 0; i < n; i++)
                e = e->next;
            if(!e) return head->next;
            while(e->next){
                s = s->next;
                e = e->next;
            }
            s->next = s->next->next;
            return head;
        }
    };
  • 相关阅读:
    Python语言程序设计(1)--实例1和基本知识点
    前端学习笔记--函数
    知乎推荐书籍整理
    第六周周总结
    第五周总结
    第四周周总结
    第三周周总结
    第二周总结
    第一周总结
    项目目标
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10704307.html
Copyright © 2011-2022 走看看