leetcode:Remove Nth Node From End of List

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
};

  

以上是关于leetcode:Remove Nth Node From End of List的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] remove nth node from the end of list 删除链表倒数第n各节点

Remove Nth Node From End of List

Nth to Last Node in List

19. Remove Nth Node From End of List

Remove Nth Node From End of List

Remove Nth Node From End of List