美文网首页
19. Remove Nth Node From End of

19. Remove Nth Node From End of

作者: Al73r | 来源:发表于2017-09-27 00:09 被阅读0次

    题目

    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.

    分析

    简单的链表操作,不多说,直接上代码。

    实现一

    /**
     * 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;
            int length=1;
            ListNode * p=head;
            while(p->next!=NULL){
                p = p->next;
                length++;
            }
            if(length>n){
                p=head;
                for(int i=0; i<length-n-1; i++){
                    p = p->next;
                }
                p->next=p->next->next;
            }
            else{
                head=head->next;
            }
    
            return head;
        }
    };
    

    思考一

    提交之后发现自己只打败了2.8%的用户,内心是崩溃的。简单的链表删除还有什么花头吗。遂查看别人的代码以及题解,发现也差不多啊。后来发现是提交时段的问题,重新用这段代码提交一次就好了=_=

    相关文章

      网友评论

          本文标题:19. Remove Nth Node From End of

          本文链接:https://www.haomeiwen.com/subject/diadextx.html