1. 程式人生 > >【leetcode】19. Remove Nth Node From End of List

【leetcode】19. Remove Nth Node From End of List

log become 兩個 str note count con not one

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.

Tips:給一個鏈表,以及一個整數n,從鏈表中將倒數第n個結點刪除。

解法一:遍歷兩遍,第一次計算鏈表總長度,第二次刪除鏈表倒數第n個結點。

public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head==null ||n<0) return null;
        ListNode headnew1=head;
        ListNode headnew2=headnew1;
        int count=1,len=0;
        while(head!=null){
            len
++; head=head.next; } if(len==n) return headnew1.next; while(headnew1!=null){ if(count==len-n){ ListNode next=headnew1.next; headnew1.next=next.next; break; } headnew1=headnew1.next; count
++; } return headnew2; }

解法二:只遍歷一遍,但是設置兩個指針,中間間隔n個結點。當fast指針的下一個指針為null時,slow指針的下一個即為要刪除的結點。

public ListNode removeNthFromEnd2(ListNode head, int n) {
        //便利一遍。
        if (head==null ||n<0) return null;
        ListNode node=new ListNode(0);
        node.next=head;
        ListNode fast=node;
        ListNode slow=node;
        ListNode newHead=slow;
        for(int i=1;i<=n;i++){
            fast=fast.next;
        }
        while(fast.next!=null){
            fast=fast.next;
            slow=slow.next;
        }
        slow.next=slow.next.next;
        return newHead.next;
    }

【leetcode】19. Remove Nth Node From End of List