LeetCode---876.链表的中间结点

题目来源:https://leetcode-cn.com/problems/middle-of-the-linked-list/description/

题目描述:

 该题目有两种做法,第一种比较容易想到,但是时间复杂度较高。

第一种:

这种做法比较简单,先遍历一遍链表计算出链表的结点个数,然后跑到length/2的位置就行了

代码如下:

struct ListNode* middleNode(struct ListNode* head) {
    if(head==NULL||head->next==NULL){
        return head;
    }
    int length=0;
    struct ListNode* p;
    for(p=head;p;p=p->next){
        length++;
    }
    p=head;
    for(int i=0;i<length/2;p=p->next,i++);
    return p;
}

第二种:

这个做法就是利用两个指针,一个快指针,一个慢指针。两个指针从head开始遍历。快指针一次跑两步,慢指针一次跑一步。当快指针遍历完一个链表之后,慢指针就跑到了中间节点。然后再根据题目要求修改(因为当节点个数为偶数时,有时候要求是靠前的节点,有时要求靠后的结点。本题要求的是靠后的结点)。

代码如下:

struct ListNode* middleNode(struct ListNode* head) {
    if(head==NULL||head->next==NULL){
        return head;
    }
    struct ListNode* fastp=head;
    struct ListNode* slowp=head;
    while(fastp->next&&fastp->next->next){
        fastp=fastp->next->next;
        slowp=slowp->next;
    }
    if(fastp->next){
        return slowp->next;
    }else{
        return slowp;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39241239/article/details/82843490