反转链表光是O(N)要求可以先存入数组再从尾部读入单链表。
若是要求常数附件空间,代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef struct node Node; 5 typedef struct node List; 6 struct node { 7 int item; 8 Node* Next; 9 }; 10 11 List ReverseList(List* list) 12 { 13 Node* TempNode = list; 14 Node* PrevNode = NULL; 15 Node* NextNode = list->Next; 16 17 while (NextNode != NULL) { 18 TempNode->Next = PrevNode; 19 PrevNode = TempNode; 20 TempNode = NextNode; 21 NextNode = NextNode->Next; 22 } 23 TempNode->Next = PrevNode; 24 return TempNode; 25 }
时间: 2024-10-09 18:05:09