学习时间:
2023年1月21日
题目描述:
题解分享:
// 作 者 : 繁 华 倾 夏
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h> // 调用malloc函数
// 力扣(LeetCode):876. 链表的中间结点
// Definition for singly-linked list. 单向链表的定义
struct ListNode {
int val;
struct ListNode *next;
};
// head:链表头节点
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode* show = head; // 利用快慢指针
struct ListNode* fast = head; // 建立两个指针指向head结点
while (fast && fast->next) { // 结束条件为fast或fast的next为空
show = show->next; // show每循环执行一次
fast = fast->next; // fast每循环执行两次
fast = fast->next;
}
return show; // 返回show慢指针
}
// 从尾部插入数据
void SListPushBack(struct ListNode** pphead, int x) {
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->val = x;
newnode->next = NULL;
if (*pphead == NULL) {
*pphead = newnode;
}
else {
// 找到尾节点
struct ListNode* tail = *pphead;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = newnode;
}
}
// 打印链表
void SListPrint(struct ListNode* phead)
{
struct ListNode* cur = phead;
while (cur != NULL) {
printf("%d->", cur->val);
cur = cur->next;
}
printf("NULL\n");
}
// 测试用例
// 输入 [1, 2, 3, 4, 5]
// 输出 此列表中的结点 3 (序列化形式:[3, 4, 5])
int main() {
struct ListNode* plist = NULL; // 建立空链表
SListPushBack(&plist, 1); // 为链表插入数据
SListPushBack(&plist, 2);
SListPushBack(&plist, 3);
SListPushBack(&plist, 4);
SListPushBack(&plist, 5);
struct ListNode* re = middleNode(plist);
SListPrint(re); // 打印链表
return 0;
}
【繁华倾夏】【每日力扣题解分享】【Day7】