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

    分析:题意为给一个链表,删除链表末端第n个节点然后返回头节点。

    思路:利用双指针思想,两个指针之间间隔n-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==NULL) return NULL;
            
            ListNode *p,*q,*temp;
            p=head;
            q=head;
            temp=NULL;
            for(int i=0; i<n-1; i++){
                q=q->next;
            }
            
            while(q->next){
                temp=p;
                q=q->next;
                p=p->next;
            }
            
            if(temp==NULL){   //这种情况下,即n=1,删除的是头节点
                head=p->next;
                delete p;
            }
            else{
                temp->next=p->next;
                delete p;
            }
            
            return head;
        }
    };
    

      

  • 相关阅读:
    数据链路层
    补码加减法
    matlab函数
    HDU2159_二维完全背包问题
    HDU2844买表——多重背包初探
    HDU1025贫富平衡
    最大m段子段和
    01背包浮点数情况
    第K大01背包
    HDU2955 01背包
  • 原文地址:https://www.cnblogs.com/carsonzhu/p/5201606.html
Copyright © 2011-2022 走看看