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;
        }
    };
  • 相关阅读:
    浅谈Java中的栈和堆
    Java运行时内存划分
    浅谈Static
    浅谈同一家公司多个系统,共用登录用户名和密码
    浅谈Final
    浅谈StringBuffer
    浅谈加密算法BCrypt
    序列表 批量的含义
    安装activemq和java代码实现生产和消费
    Restful
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3640806.html
Copyright © 2011-2022 走看看