题目
a.编写一个非递归过程以O(N)时间反转单链表.
*b.使用常数附加空间编写一个过程以O(N)时间反转单链表.
我自己写的
全部的练习是
a.编写一个非递归过程以O(N)时间反转单链表.
*b.使用常数附加空间编写一个过程以O(N)时间反转单链表.
我自己写的
- int reverser(link **head)
- {
- link *b,*a,*tmp;
- assert(NULL != head);
- assert(NULL != *head);
- b = *head;
- a = b->next;
- if (!a) return EXIT_SUCCESS;
- while(a) {
- tmp = a->next;
- a->next = b;
- b = a;
- a = tmp;
- }
- (*head)->next = NULL;
- *head = b;
- return EXIT_SUCCESS;
- }
- /*
- exercese 3.12
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <assert.h>
- typedef struct link_t link;
- struct link_t{
- int a;
- link *next;
- };
- int reverser(link **head)
- {
- link *b,*a,*tmp;
- assert(NULL != head);
- assert(NULL != *head);
- b = *head;
- a = b->next;
- if (!a) return 0;
- while(a) {
- tmp = a->next;
- a->next = b;
- b = a;
- a = tmp;
- }
- (*head)->next = NULL;
- *head = b;
- return EXIT_SUCCESS;
- }
- int main(void)
- {
- int i;
- link *p,*tmp, *last;
- /* malloc head */
- p = (link*)malloc(sizeof(link));
- if(!p) return -1;
- p->a = 0;
- p->next = NULL;
- last = p;
- /* alloc 9 more */
- for(i = 1; i < 10 ; i++) {
- tmp = (link*)malloc(sizeof(link));
- /* take care the memory allocated are not freed by hand */
- if(!tmp) return -1;
- last->next = tmp;
- tmp->a = i;
- tmp->next = NULL;
- last = tmp;
- }
- reverser(&p);
- for(tmp = p; tmp; tmp = tmp->next) {
- printf("tmp/t%d/n", tmp->a);
- }
- /* take care the memory allocated */
- return EXIT_SUCCESS;
- }