练习题 3.12

题目
 a.编写一个非递归过程以O(N)时间反转单链表.
*b.使用常数附加空间编写一个过程以O(N)时间反转单链表.

我自己写的
  1. int reverser(link **head)
  2. {
  3.     link    *b,*a,*tmp;
  4.     assert(NULL != head);
  5.     assert(NULL != *head);
  6.     b = *head;
  7.     a = b->next;
  8.     if (!a) return EXIT_SUCCESS;
  9.     while(a) {
  10.         tmp = a->next;
  11.         a->next = b;
  12.         b = a;
  13.         a = tmp;
  14.     }
  15.     (*head)->next = NULL;
  16.     *head = b;
  17.     return EXIT_SUCCESS;
  18. }
全部的练习是
  1. /* 
  2.    exercese 3.12
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <assert.h>
  8. typedef struct link_t link;
  9. struct link_t{
  10.     int     a;
  11.     link    *next;
  12. };
  13. int reverser(link **head)
  14. {
  15.     link    *b,*a,*tmp;
  16.     assert(NULL != head);
  17.     assert(NULL != *head);
  18.     b = *head;
  19.     a = b->next;
  20.     if (!a) return 0;
  21.     while(a) {
  22.         tmp = a->next;
  23.         a->next = b;
  24.         b = a;
  25.         a = tmp;
  26.     }
  27.     (*head)->next = NULL;
  28.     *head = b;
  29.     return EXIT_SUCCESS;
  30. }
  31. int main(void)
  32. {
  33.     int     i;
  34.     link    *p,*tmp, *last;
  35.     /* malloc head */
  36.     p = (link*)malloc(sizeof(link));
  37.     if(!p) return -1;
  38.     p->a = 0;
  39.     p->next = NULL;
  40.     last = p;
  41.     /* alloc 9 more */
  42.     for(i = 1; i < 10 ; i++) {
  43.         tmp = (link*)malloc(sizeof(link));
  44.         /* take care the memory allocated are not freed by hand */
  45.         if(!tmp) return -1;
  46.         last->next = tmp;
  47.         tmp->a = i;
  48.         tmp->next = NULL;
  49.         last = tmp;
  50.     }
  51.     reverser(&p);
  52.     for(tmp = p; tmp; tmp = tmp->next) {
  53.         printf("tmp/t%d/n", tmp->a);
  54.     }
  55.     /* take care the memory allocated */
  56.     return EXIT_SUCCESS;
  57. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值