19. 刪除鏈表的倒數第N個節點

19. 刪除鏈表的倒數第N個節點

一、題目介紹

給定一個鏈表,刪除鏈表的倒數第 n 個節點,而且返回鏈表的頭結點。node

試題連接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/測試

二、java

2.一、遍歷兩次

public static ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || head.next == null) return null;
        //求鏈表長度
        ListNode p = head;
        int size = 0;
        while (p != null)  {
            size++;
            p = p.next;
        }

        if(n == size) return head.next;

        p = head;
        for(int i = 2;i <= size - n;i++ ) {
            p = p.next;
        }

        p.next = p.next.next;

        return head;
    }

測試結果:3d

2.一、遍歷一次

public static ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || head.next == null) return null;
        //求鏈表長度
        ListNode p = head;
        int flag = 0;
        while (p != null && p.next != null) {
            ListNode temp = p.next;
            for(int i = 0;i < n;i++) {
                if(temp == null) {
                    flag = 1;
                    break;
                }
                temp = temp.next;
            }
            if(flag == 1) {
                return head.next;
            }
            if(temp != null) {
                p = p.next;
            }else {
                p.next = p.next.next;
                return head;
            }
        }
        return head;
    }

測試結果:code

三、C語言

3.一、遍歷兩次

struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    if(head == NULL || head->next == NULL) return NULL;
    //求鏈表長度
    struct ListNode* p = head;
    int size = 0;
    while (p != NULL)  {
        size++;
        p = p->next;
    }

    if(n == size) return head->next;

    p = head;
    for(int i = 2;i <= size - n;i++ ) {
        p = p->next;
    }

    p->next = p->next->next;

    return head;
}

測試結果:blog

3.一、遍歷一次

struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    if(head == NULL || head->next == NULL) return NULL;
    //求鏈表長度
    struct ListNode* p = head;
    int flag = 0;
    while (p != NULL && p->next != NULL) {
        struct ListNode* temp = p->next;
        for(int i = 0;i < n;i++) {
            if(temp == NULL) {
                flag = 1;
                break;
            }
            temp = temp->next;
        }
        if(flag == 1) {
            return head->next;
        }
        if(temp != NULL) {
            p = p->next;
        }else {
            p->next = p->next->next;
            return head;
        }
    }
    return head;
}

測試結果:leetcode

相關文章
相關標籤/搜索