[leetcode 19] Remove Nth Node From End of List

来源:互联网 发布:iphonex监控预约软件 编辑:程序博客网 时间:2024/04/30 04:03

Question:

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无效情况。

因为给的是倒数第n位,所以利用两个指针就可以了,初始化为head,第一个指针q比第二个指针p多走n步。如果q先走n步后为NULL,则说明要删除的为正数第一个节点,直接将head = head->next即可,否则,p q一起走,知道q->next为NULL,p指向的为要删除节点的前一个节点。


代码如下:

<span style="font-size:14px;">/** * 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) {        ListNode *p,*q;        p = head;        q = head;        while(n--){            q = q->next;        }        if(q != NULL){            while(q->next != NULL){                p = p->next;                q = q->next;            }            p->next = p->next->next;        }        else{            head = head->next;        }        return head;    }};</span>


0 0
原创粉丝点击