目录
题目
给定一个头结点为
head
的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。
思路
思路1:遍历得到节点数,然后返回中间的节点
思路2:快慢节点,slow每次只走一步,fast每次走两步。
代码
struct ListNode* middleNode(struct ListNode* head){
struct ListNode* cur = head;
int num = 0;
while (cur)
{
num++;
cur = cur->next;
}
num = (num % 2 == 0) ? (num / 2 + 1) : ((num + 1) / 2);
cur = head;
for (int i = 1; i < num; i++)
{
cur = cur->next;
}
return cur;
}
完整代码
#define _CRT_SECURE_NO_WARNINGS 1
// 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点
#include<stdio.h>
#include<stdlib.h>
typedef struct SList
{
int val;
struct SList* next;
}SLTNode;
SLTNode* createlist(int* arr, int z)
{
SLTNode* head = NULL;
SLTNode* tail = NULL;
for (int i = 0; i < z; i++)
{
SLTNode* newnode = (SLTNode*)malloc(sizeof(struct SList));
if (newnode == NULL)
{
perror("malloc fail");
exit(-1);
}
else
{
newnode->val = *(arr + i);
newnode->next = NULL;
}
if (head == NULL)
{
head = newnode;
tail = newnode;
}
else
{
tail->next = newnode;
tail = newnode;
}
}
return head;
}
void SLTPrint(SLTNode* head)
{
SLTNode* cur = head;
while (cur)
{
printf("%d->", cur->val);
cur = cur->next;
}
printf("NULL\n");
}
SLTNode* middleNode(SLTNode* head)
{
SLTNode* cur = head;
int num = 0;
while (cur)
{
num++;
cur = cur->next;
}
num = (num % 2 == 0) ? (num / 2 + 1) : ((num + 1) / 2);
cur = head;
for (int i = 1; i < num; i++)
{
cur = cur->next;
}
return cur;
}
void test1()
{
// 通过数组初始化单链表
int arr[] = { 1, 2, 3, 4, 5, 6};
SLTNode* plist = createlist(arr, sizeof(arr) / sizeof(arr[0]));
SLTPrint(plist);
// 返回中间节点
SLTNode* mid = middleNode(plist);
SLTPrint(mid);
}
int main()
{
// 返回中间节点
test1();
return 0;
}