首页 > 代码库 > 反序单向链表

反序单向链表

菜菜……我的想法:让后者的next连接前者……

技术分享
 1 #include <stdio.h> 2  #include <stdlib.h> 3  4  struct List  5  { 6      int number; 7      struct List * next; 8  }; 9 10  struct List * reverse(struct List * head);11 12  int main(void)13  {14      struct List * current, * temp;15      struct List * prev = NULL, * head = NULL;16      int num;17 18      while(scanf("%d", &num) == 1)19      {20          current = (struct List*)malloc(sizeof(struct List));21          if(head == NULL)22              head = current;23          else24              prev->next = current;25          current->number = num;26          current->next = NULL;27          prev = current;28      }29      current = reverse(head);30      while(current != NULL)31      {32          printf("%d ", current->number);33          current = current->next;34      }35      return 0;36  }37  /*38  /* 反序一个单向链表函数39 */40 struct List * reverse(struct List * head)41  {42      struct List * temp;43      struct List * prev;44      struct List * current;45 46      prev = NULL;47      current = head;48 49      while(current != NULL)50      {51          temp = current->next;52          current->next = prev;53          prev = current;54          current = temp;55      }56      head = prev;57      return head;58  }
View Code

 

反序单向链表