zoukankan      html  css  js  c++  java
  • leetcode 19. 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.

    思路:
    最直接的思路,应该是先统计链表节点的个数num,然后再找到第num-n-1那个节点x,把那个x节点的next指向x->next->next就行了。但是这个很明显不能在一遍遍历解决。
    可以用双指针的思想初始p=head q=head。开始走n个节点到p,然后从p->next开始,和q一起走,知道p->next为nullptr,那么此时的q就是上个思路的x节点。那么q->next=q->next->next就行了。
    代码如下:

     * 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 || head->next == NULL)
                return NULL;
            ListNode *p = head;
            ListNode *q = head;
            while(--n >= 0) p = p->next;
            if(p == NULL) return head->next;
            
            p = p->next;
            while(p != NULL) {
                p = p->next;
                q = q->next;
            }
            q->next = q->next->next;
            return head;
        }
    };
    
  • 相关阅读:
    SQL Server 2005 System Views Map
    SQL语句实现移动数据库文件
    重写系统存储过程:sp_spaceused
    MSSQL2005中的架构与用户
    根据时间段计算有n年n月n天
    Linux中的环境变量 (转)
    计算工龄,格式为n年n月n天
    学习递归CTE
    分区表应用例子
    根据备份文件直接还原数据库
  • 原文地址:https://www.cnblogs.com/pk28/p/7709582.html
Copyright © 2011-2022 走看看