Technology Sharing

C Language Notes 32 •OJ Problem on the Classic Algorithm for a Single Linked List - 4. Find the Middle Node of a Linked List •

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. Problem

Give you the head node of the singly linked listhead, please find and return the middle node of the linked list.

If there are two middle nodes, the second middle node is returned.

2. Code implementation (fast and slow pointers)

  1. //4.查找链表的中间结点
  2. #define _CRT_SECURE_NO_WARNINGS 1
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <assert.h>
  6. typedef int SLTDataType;
  7. typedef struct SListnode
  8. {
  9. SLTDataType val;
  10. struct SListnode* next;
  11. }ListNode;
  12. ListNode* createNode(SLTDataType val)
  13. {
  14. ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
  15. if (newnode == NULL)
  16. {
  17. perror("malloc");
  18. exit(1);
  19. }
  20. newnode->val = val;
  21. newnode->next = NULL;
  22. return newnode;
  23. }
  24. struct ListNode* middleNode(struct ListNode* head)
  25. {
  26. if (head == NULL)
  27. {
  28. return head;
  29. }
  30. ListNode* slow, * fast;
  31. slow = fast= head;
  32. while (fast && fast->next)
  33. {
  34. slow = slow->next;
  35. fast = fast->next->next;
  36. }
  37. return slow;
  38. }
  39. int main()
  40. {
  41. ListNode* node1, * node2, * node3, * node4, * node5, * node6;
  42. node1 = createNode(1);
  43. node2 = node1->next = createNode(2);
  44. node3 = node2->next = createNode(3);
  45. node4 = node3->next = createNode(4);
  46. node5 = node4->next = createNode(5);
  47. //node6 = node5->next = createNode(6);//创建一个链表
  48. ListNode* node = middleNode(node1);
  49. printf("%d", node->val);
  50. return 0;
  51. }