- /*
- * reserve the linked list without circular 链表反向
- */
- #include <stdio.h>
- #include <stdlib.h>
- struct linklist
- {
- struct linklist *next;
-
- int key;
- };
- void
- printf_linklist (struct linklist *head)
- {
- struct linklist *lnode;
-
- if (head == NULL)
- printf ("%% linklist is NULL\n");
-
- lnode = head;
- printf (" Linklist : ");
- for (; lnode; lnode = lnode->next)
- {
- printf (" %d ", lnode->key);
- }
-
- return;
- }
- struct linklist *
- reverse_linklist (struct linklist *head)
- {
- struct linklist *re_link;
- struct linklist *link_tmp;
- struct linklist *link_next;
-
- if (head == NULL)
- return NULL;
- re_link = head;
- link_next = head->next;
- re_link->next = NULL;
-
- while (link_next)
- {
- link_tmp = link_next;
-
- link_next = link_next->next;
-
- link_tmp->next = re_link;
- re_link = link_tmp;
- }
-
- return re_link;
- }
- struct linklist *
- create_linklist (int numb)
- {
- int i;
- struct linklist *lists[numb];
- struct linklist *lnode;
- struct linklist *lnode_n;
- for (i = 0; i < numb; i++)
- {
- lists[i] = (struct linklist *) malloc (sizeof (struct linklist));
- if (lists[i] == NULL)
- break;
-
- lists[i]->key = i;
- lists[i]->next = NULL;
- if (i > 0)
- lists[i-1]->next = lists[i];
- }
-
- if (i < numb)
- {
- for (lnode = lists[0]; lnode; lnode = lnode_n)
- {
- lnode_n = lnode->next;
- free (lnode);
- lnode = NULL;
- }
-
- return NULL;
- }
-
- return lists[0];
- }
- void
- destroy_linklist (struct linklist *head)
- {
- struct linklist *lnode;
- struct linklist *lnode_n;
-
- if (head == NULL)
- return;
-
- for (lnode = head; lnode; lnode = lnode_n)
- {
- lnode_n = lnode->next;
- free (lnode);
- lnode = NULL;
- }
-
- return;
- }
- int
- main (void)
- {
- int numb;
- struct linklist *head;
-
- printf ("\n pls enter the listnode numb : ");
- scanf ("%d", &numb);
-
- head = create_linklist (numb);
- printf ("\n before reverse :");
- printf_linklist (head);
-
- head = reverse_linklist (head);
- printf ("\n after reverse :");
- printf_linklist (head);
-
- destroy_linklist (head);
-
- return 0;
- }
运行结果:(gcc, 今天利用这个特意试了下gdb 调试)