876. 链表的中间结点

876. 链表的中间结点

1、题目描述

给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

试题链接:https://leetcode-cn.com/problems/middle-of-the-linked-list/

2、java编程语言实现

2.1、常规做法

    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;
    }

测试结果:

2.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;
    }

测试结果:

3、C语言实现

3.1、常规做法

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;
}

测试结果:

3.2、快慢指针做法

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;
}

测试结果:

posted @ 2020-03-02 15:40  孤傲的咸鱼  阅读(419)  评论(0编辑  收藏  举报