系列文章目录
一、题目描述
二、代码如下:
解法一:遍历两次
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* middleNode(struct ListNode* head){
struct ListNode * cur=head;
int len=1;//记录总节点个数
//移动nextcur至尾节点、
while(cur->next!=NULL)
{
cur=cur->next;
len++;
}
//此时nextcur指向尾节点,i为节点个数
//让cur向后移i/2
int i=0;
for(i = 0 ;i<len/2;i++)
{
head=head->next;
}
return head;
}
解法二:快慢指针,遍历一次
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* middleNode(struct ListNode* head){
//快慢指针
struct ListNode *fast=head;
struct ListNode *slow=head;
while(fast&&fast->next)
{
fast=fast->next->next;
slow=slow->next;
}
return head=slow;
}