标签:include creat struct size 查找 class head str printf
1 #include <stdio.h> 2 #include <stdlib.h> 3 /* 4 查找链表中间的结点。 5 思路1:求长度:中间结点 = len/2 6 思路2:定义两个指针p1,p2指向头结点,p1走一步,p2走两步,当p2指向尾结点的下一个结点的时候,p1指向中间结点。 7 疑问:比如链表有5个结点,那么第3个是中间结点毫无疑问,但是如果6个结点,那么第3个算中间结点,还是第4个算中间结点呢? 8 */ 9 typedef struct node 10 { 11 int data; 12 struct node * next; 13 }NODE; 14 NODE * createList() 15 { 16 NODE * head = (NODE *)malloc(sizeof(NODE)); 17 head->next = NULL; 18 19 return head; 20 } 21 void insertNode(NODE *head,int insertData) 22 { 23 NODE * sur = (NODE *)malloc(sizeof(NODE)); 24 sur->data = insertData; 25 26 sur->next = head->next; 27 head->next = sur; 28 29 } 30 void traverList(NODE *head) 31 { 32 int i = 1; 33 head = head->next; 34 while(head) 35 { 36 printf("第%d结点 = %d\n",i,head->data); 37 head = head->next; 38 i++; 39 } 40 } 41 NODE *middleList(NODE *head) 42 { 43 NODE *p1,*p2; 44 p1 = p2 = head; 45 while(p2) 46 { 47 p1 = p1->next; 48 p2 = p2->next; 49 if(p2 !=NULL) 50 p2 = p2->next; 51 52 } 53 return p1; 54 } 55 int main(void) 56 { 57 NODE *head = createList(); 58 for(int i = 0;i<5;i++) 59 insertNode(head,rand()%100); 60 traverList(head); 61 NODE * p1 = middleList(head); 62 printf("中间结点数据 = %d\n",p1->data); 63 return 0; 64 }
标签:include creat struct size 查找 class head str printf
原文地址:https://www.cnblogs.com/wangchaomahan/p/9734639.html