zoukankan      html  css  js  c++  java
  • Remove Nth Node From End of List

    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.

    思路:这道题从尾结点开始删除给定索引的值,然后再输出删除后的结点。我们可以使用两个指针pPost,pPre来解这道题,而且还要保存后面指针的前一结点为删除指定结点做准备。想让pPre先走n-1步,然后循环pPre和pPost共同起步行走,每一次之前都要把pPost保存下来,直到pPre->next为空循环结束。然后判断pTemp。

    /**
     * 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 *pTemp=NULL;
            ListNode *pPre=head;
            ListNode *pPost=head;
            for(int i=0;i<n-1;i++)
                pPre=pPre->next;
            while(pPre->next!=NULL)
            {
                pTemp=pPost;
                pPre=pPre->next;
                pPost=pPost->next;
            }
            if(pTemp==NULL)
            {
                head=head->next;
            }
            else
            {
                pTemp->next=pPost->next;
            }
            return head;
        }
    };
  • 相关阅读:
    2019-10-28-开源项目
    2018-8-10-win10-uwp-MetroLog-入门
    2018-5-20-C#-BBcode-转-Markdown
    2018-8-10-win10-UWP-序列化
    2018-2-13-win10-uwp-BadgeLogo-颜色
    2019-1-25-WPF-ListBox-的选择
    2019-1-5-Windows-的-Pen-协议
    android studio打印
    Java 基本数据类型
    FreeRTOS 任务通知模拟计数型信号量
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3640806.html
Copyright © 2011-2022 走看看