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;
    }
};


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

[C++]LeetCode 19: Remove Nth Node From End of List(删除链表中倒数第n个节点)

Problem: Given a linked list, remove the nth node from the end of list and return its head. For exam...

Leetcode_19_Remove Nth Node From End of List

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/41778305 Given a linked list, ...

【Leetcode】19. Remove Nth Node From End of List

方法一: 思路: (1)若链表为空,直接返回null。 (2)求链表的长度len。 (3)若n==len,则删除的是第一个节点,直接删除后返回即可。 (4)从头开始遍历链表,找到待删除节点cur,并用...

[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 examp...

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...

leetcode19~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, Gi...

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, ...
  • mcf171
  • mcf171
  • 2016年10月01日 18:15
  • 99

LeetCode 19之Remove Nth Node From End of List的Java题解(三种解法)

题目: Given a linked list, remove the nth node from the end of list and return its head. For e...

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, G...

LeetCode41/19 First Missing Positive/Remove Nth Node From End of List ****

leetcode41 First Missing Positive 题目: Given an unsorted integer array, find the first missing posi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode-Remove Nth Node From End of List-19
举报原因:
原因补充:

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