Remove Nth Node From End of List(删除链表的倒数第n个节点)leetcode19

Given a linked list, remove the n-th node from the end of list and return its head.

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.


code1:

 public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null)
            return null;
        ListNode number=head;
        ListNode fast=head;
        ListNode slow=head;
        ListNode pre=null;
        int count=1;
        while(number.next!=null){
            number=number.next;
            count++;
    }
        if(count==n)
            return head.next;
        for(int i=0;i<n;i++)
            fast=fast.next;
        while(fast!=null){
            fast=fast.next;
            pre=slow;
            slow=slow.next;
        }
            pre.next=slow.next;
        return head;
    }

code2:(优化后的)

 public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null)
            return null;
        ListNode number=head;
        ListNode slow=head;
        int count=1;
        while(number.next!=null){
            number=number.next;
            count++;
    }
        if(count==n)
            return head.next;
        int step=count-n;
        while(step>1){
            slow=slow.next;
            step--;
    }
        slow.next=slow.next.next;
        return head;
        
    }

猜你喜欢

转载自blog.csdn.net/m0_37402140/article/details/80465469