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

来源:互联网 发布:边际递减效应爱情知乎 编辑:程序博客网 时间:2024/06/18 22:27

题目原文:
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即可。

0 0
原创粉丝点击