首页 > 其他 > 详细

876. 链表的中间结点

时间:2020-03-02 16:27:31      阅读:50      评论:0      收藏:0      [点我收藏+]

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

测试结果:

技术分享图片

876. 链表的中间结点

原文:https://www.cnblogs.com/xgp123/p/12395946.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!