美文网首页ACM题库~
LeetCode 19. Remove Nth Node Fro

LeetCode 19. Remove Nth Node Fro

作者: 关玮琳linSir | 来源:发表于2017-09-12 15:41 被阅读8次

    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个数字,我们的策略是两个指针,从头开始,假设倒数第五个,先让一个指针走出去五个,然后两个同时启动,当第一个到了最末尾,第二个也就到了我们最终想要的位置了。

    java代码:

    public static ListNode removeNthFromEnd(ListNode head, int n) {
    
            if (n < 1) return head;
            int i = 0;
            ListNode before = head;
            while (i < n + 1 && before != null) {
                before = before.next;
                i++;
            }
            if(i == n+1){
                ListNode after = head;
                while(before!=null){
                    before = before.next;
                    after = after.next;
                }
                ListNode temp = after.next;
                after.next = temp.next;
            }else if (i == n){
                ListNode tmep = head;
                head = head.next;
            }
            return head;
        }
    

    相关文章

      网友评论

        本文标题:LeetCode 19. Remove Nth Node Fro

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