【第22期】观点:IT 行业加班,到底有没有价值?

leetcode-Remove Nth Node From End of List-19

原创 2016年05月30日 23:46:25

删除链表的倒数第n个节点

双指针思想

/**
 * 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=head;
        ListNode* q=head;
        ListNode* pre=NULL;
        int i=n-1;
        while(i--){
            p=p->next;
        }
        // while(p!=NULL){//这里这样做会re,因为要p先后移q和pre才能移动不然就可能越界
        //     pre=q;
        //     q=q->next;
        //     p=p->next;
        // }
        while(p->next!=NULL){
            pre=q;
            q=q->next;
            p=p->next;
        }
        if(pre==NULL){
            head=q->next;
            delete q;
        }
        else{
            pre->next=q->next;
            delete q;
        }
        return head;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

LeetCode 19. Remove Nth Node From End of List(链表)

LeetCode 19. Remove Nth Node From End of List(链表)LeetCode 19 Remove Nth Node From End of List链表 问题描述...

Leetcode - Remove Nth Node From End of List

Remove Nth Node From End of List Total Accepted: 63354 Total Submissions: 234837 My Submissions Question Solution 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 no

LeetCode 19. Remove Nth Node From End of List 解题报告

19. Remove Nth Node From End of List My Submissions Question Total Accepted: 94847 Total ...

[LeetCode] Remove Nth Node From End of List

Given a linked list, remove the <em style="margin

LeetCode OJ-19.Remove Nth Node From End of List

LeetCode OJ-19.Remove Nth Node From End of List题目描述 Given a linked list, remove the *n*th node fro...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)