C语言刷题 LeetCode 30天挑战 (八)快慢指针法

//Middle of the Linked List
//Given a non-empty, singly linked list with head node head , 
//return a middle node of linked list.
//If there are two middle nodes, return the second middle node

//Example 1:
//Input:1,2,3,4,5]
//0utput:Node 3from this list(Serialization:[3,4,5])
//The returned node has value 3, (The judge's serialization of this node is [3,4,5]).
//Note that we returned a ListNode object ans, such that:
//ans,val =3,ans.next,val =4,ans.next,next.val = 5, and ans.next.next.next = NULL.
//Example 2:
//Input:I[1,2,3,4,5,6]
//Output:Node 4 from this list(serialization:[4,5,6])
//Since the list has two middle nodes with values 3 and 4, we return the second one.

#include <stdio.h>
#include <stdlib.h>

// Definition for singly-linked list.
struct ListNode {
    int val;
    struct ListNode *next;
};

// Function to find the middle node
struct ListNode* middleNode(struct ListNode *head) {
    struct ListNode *slow = head;
    struct ListNode *fast = head;

    // Move slow pointer one step and fast pointer two steps
    while (fast != NULL && fast->next != NULL) {
        slow = slow->next;
        fast = fast->next->next;
    }
    
    // When fast reaches the end, slow is at the middle
    return slow;
}

// Helper function to create a new ListNode
struct ListNode* createNode(int val) {
    struct ListNode* newNode = (struct ListNode*) malloc(sizeof(struct ListNode));
    newNode->val = val;
    newNode->next = NULL;
    return newNode;
}

// Helper function to print the linked list from a given node
void printList(struct ListNode* node) {
    while (node != NULL) {
        printf("%d ", node->val);
        node = node->next;
    }
    printf("\n");
}

int main() {
    // Example 1: [1, 2, 3, 4, 5]
    struct ListNode* head = createNode(1);
    head->next = createNode(2);
    head->next->next = createNode(3);
    head->next->next->next = createNode(4);
    head->next->next->next->next = createNode(5);
    
    struct ListNode* middle = middleNode(head);
    printf("Middle node value: %d\n", middle->val);
    printf("List from middle node: ");
    printList(middle);
    
    // Example 2: [1, 2, 3, 4, 5, 6]
    struct ListNode* head2 = createNode(1);
    head2->next = createNode(2);
    head2->next->next = createNode(3);
    head2->next->next->next = createNode(4);
    head2->next->next->next->next = createNode(5);
    head2->next->next->next->next->next = createNode(6);
    
    middle = middleNode(head2);
    printf("Middle node value: %d\n", middle->val);
    printf("List from middle node: ");
    printList(middle);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

7yewh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值