fork download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct Node{
  5. int data;
  6. struct Node* next;
  7. }node;
  8.  
  9. node *push(node *head, int k);
  10. node *list_invert(node *head);
  11. void print_list(node *head);
  12. void listfree(node *head);
  13.  
  14. //Insert from head like stack.
  15. node* push(node *head, int k){
  16. node *new = malloc(sizeof(node));
  17. new -> data = k;
  18. new -> next = NULL;
  19. if(head == NULL){
  20. return new;
  21. }
  22. else{
  23. new -> next = head; //We have to set the pointer of inserted node
  24. head = new;
  25. return head;
  26. }
  27.  
  28. }
  29.  
  30. node *list_invert(node *head){
  31. node *curr = head, *prev = NULL, *succ = curr -> next;
  32. while(succ != NULL){ //最後一個node不會做下列操作
  33. curr -> next = prev;
  34. prev = curr;
  35. curr = succ;
  36. succ = succ -> next;
  37. }
  38. curr -> next = prev; // 把最後一個node的pointer反過來。
  39. head = curr;
  40. return head;
  41. }
  42.  
  43. void print_list(node* head){
  44. while(head != NULL){
  45. printf("%d -> ", head -> data);
  46. head = head -> next;
  47. }
  48. printf("NULL\n");
  49. }
  50.  
  51.  
  52.  
  53. int main(int argc, char **argv){
  54. node *head = NULL; //Empty Linked List;
  55. head = push(head, 2);
  56. head = push(head, 7);
  57. head = push(head, 15);
  58. head = push(head, 21);
  59.  
  60. print_list(head);
  61. head = list_invert(head);
  62. print_list(head);
  63.  
  64.  
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0s 4516KB
stdin
Standard input is empty
stdout
21 -> 15 -> 7 -> 2 -> NULL
2 -> 7 -> 15 -> 21 -> NULL