输出链表的中间结点
本次程序可输出链表的中间结点的数据。
1 #define _CRT_SECURE_NO_WARNINGS 1 2 #include <stdio.h> 3 #include <stdlib.h> 4 struct Node { 5 int data; 6 struct Node* next; 7 }; 8 9 struct Node* CreateList() 10 { 11 struct Node* headNode = (struct Node*)malloc(sizeof(struct Node)); 12 headNode->next = NULL; 13 return headNode; 14 } 15 16 struct Node* CreateNode(int data) 17 { 18 struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); 19 newNode->data = data; 20 newNode->next = NULL; 21 return newNode; 22 } 23 24 int ListLength(struct Node* headNode) 25 { 26 int len = 0; 27 while (headNode) 28 { 29 headNode = headNode->next; 30 len++; 31 } 32 return len; 33 } 34 35 void InsertNode(struct Node* headNode, int index, int data) 36 { 37 if (!headNode || index <= 0 || index > ListLength(headNode)) { 38 return -1; 39 } 40 else if (index == 1) { 41 struct Node* newNode = CreateNode(data); 42 newNode->next = headNode->next; 43 headNode->next = newNode; 44 } 45 else { 46 struct Node* temp = headNode; 47 for (int i = 0; i < index - 1; i++) { 48 temp = temp->next; 49 } 50 struct Node* newNode = CreateNode(data); 51 newNode->next = temp->next; 52 temp->next = newNode; 53 } 54 } 55 56 void PrintList(struct Node* headNode) 57 { 58 struct Node* pMove = headNode->next; 59 while (pMove) 60 { 61 printf("%d ", pMove->data); 62 pMove = pMove->next; 63 } 64 printf("\n"); 65 } 66 67 void MiddleDataOfList(struct Node* headNode) //输出中间结点的数据 68 { 69 struct Node* posNode = headNode; 70 int i, len; 71 if (!headNode) { 72 return -1; 73 } 74 len = ListLength(headNode) / 2; 75 for (i = 0; i < len; i++) { 76 posNode = posNode->next; 77 } 78 printf("中间结点的数据是:%d\n", posNode->data); 79 } 80 81 int main() 82 { 83 int i, pos, data, k; 84 struct Node* pl = CreateList(); 85 while (1) 86 { 87 printf("1.往链表中输入数据;2.打印链表;3.打印中间结点;4.退出:"); 88 scanf("%d", &i); 89 if (i == 1) { 90 printf("请输入你想要添加的位置:"); 91 scanf("%d", &pos); 92 printf("请输入你想要添加的数据:"); 93 scanf("%d", &data); 94 InsertNode(pl, pos, data); 95 } 96 else if (i == 2) { 97 printf("链表为:\n"); 98 PrintList(pl); 99 } 100 else if (i == 3) { 101 MiddleDataOfList(pl); 102 } 103 else if (i == 4) { 104 break; 105 } 106 } 107 return 0; 108 }