zoukankan      html  css  js  c++  java
  • leetcode 去除单链表倒数第k个节点

    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?

    关键:

    1、三个指针,一个用于找到链表尾节点,ListNode* front;一个用于指向被删除节点,ListNode* del;一个用于指向被删除节点前一个节点,ListNode* back。

    2、front先往前移动n步,然后front,del和back一起移动。

    3、三种特殊情况,链表长度为0;链表长度为1;删除的节点是头节点。

    /**
     * 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->next==NULL){
                return NULL;
            }
    
            
            ListNode* front=head;
            ListNode* del=head;
            ListNode* back=NULL;
            
            for(int i=0;i<n;i++){
                front=front->next;
            }
        
        
            while(front!=NULL){
                front=front->next;
                back=del;
                del=del->next;
            }
            
            if(back==NULL){
                return del->next;
            }else{
                back->next=back->next->next;
                return head;
            }
            
        }
    };
  • 相关阅读:
    python 进程、线程、协程感悟
    elk部署心得
    虚拟安装centos后无法上网、DNS无法解析问题解决
    mysql测试题
    爬取lol皮肤
    ping使用
    第一篇技术博客
    PADS layout修改字符时发生严重错误退出问题
    PADS 快捷键
    电容知识整理
  • 原文地址:https://www.cnblogs.com/zealousness/p/9664797.html
Copyright © 2011-2022 走看看