LeetCode--remove-nth-node-from-end-of-list

remove-nth-node-from-end-of-list

自己的方法,很笨

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(n <= 0 || head == null) return head;
        int len = 0;
        ListNode node = head;
        while(node != null){
            node = node.next;
            len++;
        }
        if(n == len){
            return head.next;
        }
        int num = len - n;
        node = head;
        while(num > 1 && node != null){
            node = node.next;
            num--;
        }
        node.next = node.next.next;
        return head;
    }
}

  

这个居然有快慢指针的方法,厉害了,贴上方法!!!

class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        ListNode *pfast=head;
        ListNode *plow=head;
        while(n--)
            pfast=pfast->next;
        if(pfast==NULL)
            return head->next;
        while(pfast->next!=NULL){
            pfast=pfast->next;
            plow=plow->next;
        }
        pfast=plow->next;
        plow->next=plow->next->next;
        //delete plow->next;
        return head;
    }
};

  

posted @ 2018-07-14 10:17  SkyeAngel  阅读(116)  评论(0编辑  收藏  举报