访问链表中的某个元素(快慢指针)

题目一:访问中间元素

题目信息:

(1)题目连接:

leetcode中间元素访问

(2)题目信息:

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Example 1:
在这里插入图片描述

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:
在这里插入图片描述

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes 
with values 3 and 4,
 we return the second one.

Constraints:

The number of nodes in the list is in the range [1, 100].
1 <= Node.val <= 100

题目解答:

(1)方法一:遍历

这种方法是最容易想到的,第一遍遍历计算节点的个数,第二遍遍历找到中间的节点。
这个方法由于过于简单,并且我也懒得画图了,所以就不作图解了。直接上代码:

/*
 * Definition for singly-linked list.
 * struct ListNode 
 * {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* middleNode(struct ListNode* head)
{
    if(head==NULL)
    {
        return NULL;
    }
    int count=1;
    struct ListNode*tail=head;
    while(tail->next!=NULL)
    {
        tail=tail->next;
        count++;
    }

    int mid=(count/2)+1;
    int n=1;
    struct ListNode*cur=head;
    while(n!=mid)
    {
        if(cur!=NULL)
        cur=cur->next;
        n++;
    }
    return cur;

}

在这里插入图片描述
那么我们能只遍历一遍就得到结果吗?此时我们就需要了解一下方法二。

(1)方法二:快慢指针

当节点个数为奇数的时候:
在这里插入图片描述
当节点个数为偶数的时候:
在这里插入图片描述

/*
 * Definition for singly-linked list.
 * struct ListNode
 * {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* middleNode(struct ListNode* head)
{
    struct ListNode*quick=head,*slow=head;
    while(quick!=NULL&&quick->next!=NULL)
    {
        slow=slow->next;
        quick=quick->next->next;
    }
    return slow;
}

题目二:访问倒数第K个元素

题目信息:


leetcode访问倒数第k个元素

题目详解:

这道题并不是类似访问中间节点,或者三分之一节点的倍数问题,所以我们的快慢指针不能快在步长。那么我们如何使用快慢指针呢?

如下图所示,此时我们设置的两个快慢指针的步长都设置为一个节点。但是我们要让快指针提前出发k个节点。

(1)图解

在这里插入图片描述

(2)代码

struct ListNode* FindKthToTail(struct ListNode* pListHead, int k )
 {
     if(pListHead==NULL)
     {
         return NULL;
     }
    struct ListNode *tail=pListHead;
    int count=1;
    while(tail->next!=NULL)
    {
        tail=tail->next;
        count++;
    } 
    if(k>count||k<=0)
    {
        return NULL;
    }
    else
    {
        struct ListNode *slow=pListHead;
        struct ListNode *quick=pListHead;
        while(k--)
        {
            quick=quick->next;
        }
        while(quick!=NULL)
        {
            slow=slow->next;
            quick=quick->next;
        }
        return slow;
    }

我们需要格外注意 k范围和空链表的判断!
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值