ldjhust

工欲善其事 必先利其器

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  1 #include <stdio.h>
  2 #include <assert.h>
  3 #include <malloc.h>
  4 
  5 typedef struct NODE
  6 {
  7     int data;
  8 
  9     struct NODE *next;
 10 }Linklist;
 11 
 12 void Reverse(Linklist *head)
 13 {
 14     assert (NULL != head);
 15 
 16     Linklist *p1 = NULL;
 17     Linklist *p2 = NULL;
 18 
 19     if ((NULL == (head->next)) || (NULL == (head->next->next)))
 20     {
 21         return;
 22     }
 23 
 24     p1 = head->next;
 25     p2 = p1->next;
 26 
 27     while (NULL != p2)
 28     {
 29         p1->next = p2->next;
 30         p2->next = head->next;
 31         head->next = p2;
 32         p2 = p1->next;
 33     }
 34 }
 35 
 36 void initialLinklist(Linklist **head)
 37 {
 38     assert (head != NULL);
 39 
 40     if (NULL == (*head = (Linklist *)malloc(sizeof(Linklist))))
 41     {
 42         printf ("Fail to malloc space to *head!\n");
 43         return;
 44     }
 45 
 46     (*head)->next = NULL;
 47 }
 48 
 49 void CreatLinklist(Linklist *head)
 50 {
 51     assert (head != NULL);
 52 
 53     int data;
 54     Linklist *p = head;
 55 
 56     printf ("Please input NODE number, end with -1:\n");
 57     scanf ("%d", &data);
 58     while (data != -1)
 59     {
 60         if (NULL == ((p->next) = (Linklist *)malloc(sizeof(Linklist))))
 61         {
 62             printf ("Fail to malloc space to head->next!\n");
 63             return;
 64         }
 65 
 66         p = p->next;
 67         p->data = data;
 68         p->next = NULL;
 69 
 70         scanf ("%d", &data);
 71     }
 72 }
 73 
 74 void PrintLinklist(Linklist *head)
 75 {
 76     assert (head != NULL);
 77 
 78     Linklist *p = head->next;
 79 
 80     while (p != NULL)
 81     {
 82         printf ("%d ", p->data);
 83 
 84         p = p->next;
 85     }
 86 
 87     printf ("\n");
 88 }
 89 
 90 void FreeLinklist(Linklist *head)
 91 {
 92     assert (head != NULL);
 93 
 94     Linklist *p = head->next;
 95 
 96     while (p != NULL)
 97     {
 98         head->next = p->next;
 99 
100         free (p);
101         
102         p = head->next;
103     }
104 
105     free (head);
106     head = NULL;
107 }
108 
109 int main(void)
110 {
111     Linklist *head = NULL;
112 
113     initialLinklist (&head);
114 
115     CreatLinklist (head);
116 
117     Reverse (head);
118 
119     PrintLinklist (head);
120 
121     FreeLinklist (head);
122 
123     return (0);
124 }

posted on 2013-04-11 10:19  ldjhust  阅读(247)  评论(0编辑  收藏  举报