1.问题
给你单链表的头结点
head
,请你找出并返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。
2.代码实现(快慢指针)
//4.查找链表的中间结点
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int SLTDataType;
typedef struct SListnode
{
SLTDataType val;
struct SListnode* next;
}ListNode;
ListNode* createNode(SLTDataType val)
{
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
if (newnode == NULL)
{
perror("malloc");
exit(1);
}
newnode->val = val;
newnode->next = NULL;
return newnode;
}
struct ListNode* middleNode(struct ListNode* head)
{
if (head == NULL)
{
return head;
}
ListNode* slow, * fast;
slow = fast= head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
int main()
{
ListNode* node1, * node2, * node3, * node4, * node5, * node6;
node1 = createNode(1);
node2 = node1->next = createNode(2);
node3 = node2->next = createNode(3);
node4 = node3->next = createNode(4);
node5 = node4->next = createNode(5);
//node6 = node5->next = createNode(6);//创建一个链表
ListNode* node = middleNode(node1);
printf("%d", node->val);
return 0;
}