876. 鏈表的中間結點

876. 鏈表的中間結點

一、題目描述

給定一個帶有頭結點 head 的非空單鏈表,返回鏈表的中間結點。編程

若是有兩個中間結點,則返回第二個中間結點。編程語言

試題連接:https://leetcode-cn.com/problems/middle-of-the-linked-list/測試

二、java編程語言實現

2.一、常規作法

public static ListNode middleNode(ListNode head) {
        if(head == null) return null;
        //定義輔助指針
        ListNode pCurrent = head;
        //獲取鏈表的長度
        int count = 0;
        while(pCurrent != null) {
            count++;
            pCurrent = pCurrent.next;
        }

        pCurrent = head;

        //若是是奇數
            for(int i = 2;i <= count/2 + 1;i++ ) {
                pCurrent = pCurrent.next;
            }
            return pCurrent;
    }

測試結果:3d

2.二、快慢指針作法

public static ListNode middleNode(ListNode head) {
        if(head == null) return null;
        //定義快慢指針
        ListNode p1 = head; //快指針
        ListNode p2 = head; //慢指針

        //1-2-3-4-5

        //p1走兩步,p2走一步
        while(p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
        }
        return p1;
    }

測試結果:指針

三、C語言實現

3.一、常規作法

struct ListNode* middleNode(struct ListNode* head){
    if(head == NULL) return NULL;
    //定義輔助指針
    struct ListNode* pCurrent = head;
    //獲取鏈表的長度
    int count = 0;
    while(pCurrent != NULL) {
        count++;
        pCurrent = pCurrent->next;
    }

    pCurrent = head;

    //若是是奇數
    for(int i = 2;i <= count/2 + 1;i++ ) {
        pCurrent = pCurrent->next;
    }
    return pCurrent;
}

測試結果:code

3.二、快慢指針作法

struct ListNode* middleNode(struct ListNode* head){
    if(head == NULL) return NULL;
    //定義快慢指針
    struct ListNode* p1 = head; //快指針
    struct ListNode* p2 = head; //慢指針

    //1-2-3-4-5

    //p1走兩步,p2走一步
    while(p2 != NULL && p2->next != NULL) {
        p1 = p1->next;
        p2 = p2->next->next;
    }
    return p1;
}

測試結果:blog

相關文章
相關標籤/搜索