Easy-题目44:19. Remove Nth Node From End of List

原创 2016年05月30日 20:33:57

题目原文:
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.
题目大意:
给出一个单链表,删除倒数第n个节点。
题目分析:
用两个指针,第一个指针p1指向头结点,然后第二个节点p2指向p1之后第n个节点(向右滑动n次)。然后并行向右滑动两个指针,直到p2为最后一个节点(p2->next==NULL),此时p1指向待删除节点的前一个节点,令p1=p1->next即可。
源码:(language:c)

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    if (!head)
        return NULL;
    struct ListNode *p1 = head;
    struct ListNode *p2 = head;
    for(int i = 0; i < n; i++)
        p2 = p2->next;
    if(!p2) 
        return head->next;

    while(p2->next) {
        p1 = p1->next;
        p2 = p2->next;
    }

    p1->next=p1->next->next;
    return head;
}

成绩:
0ms,beats 19.70%,众数0ms,80.30%
Cmershen的碎碎念:
本题有一个需要讨论的地方,就是在p2向右滑动n步的时候,有可能滑到最后一个节点的后面(即null),此时说明要删除的是头节点,直接返回head->next即可。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

19. Remove Nth Node From End of List [easy] (Python)

题目链接https://leetcode.com/problems/remove-nth-node-from-end-of-list/题目原文 Given a linked list, remov...

[LeetCode] 019. Remove Nth Node From End of List (Easy) (C++/Python)

[LeetCode] 019. Remove Nth Node From End of List (Easy) (C++/Python)
  • hcbbt
  • hcbbt
  • 2015年03月04日 19:26
  • 2134

[leetcode: Python]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 ...
  • NXHYD
  • NXHYD
  • 2017年05月19日 08:28
  • 155

LeetCode-19 Remove Nth Node From End of List(移除尾部第N个节点)

LeetCode-19 Remove Nth Node From End of List Given a linked list, remove the nth node from the end o...

LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)

链接 LeetCode题目:https://leetcode.com/problems/remove-nth-node-from-end-of-list GitHub代码:https:/...
  • gatieme
  • gatieme
  • 2016年04月07日 22:42
  • 1096

LeetCode 19 — Remove Nth Node From End of List(C++ Java Python)

题目:http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/ Given a linked list, remove t...

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

[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,并用...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Easy-题目44:19. Remove Nth Node From End of List
举报原因:
原因补充:

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