Chinaunix首页 | 论坛 | 博客
  • 博客访问: 215410
  • 博文数量: 127
  • 博客积分: 1998
  • 博客等级: 上尉
  • 技术积分: 1432
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-07 16:41
文章分类

全部博文(127)

文章存档

2014年(41)

2013年(1)

2012年(85)

分类: C/C++

2012-03-09 20:32:46

  1. /*
  2.  * =====================================================================================
  3.  *
  4.  * Filename: single_link.c
  5.  *
  6.  * Description: 实现某个单链表的逆序。
  7.  *
  8.  * Version: 1.0
  9.  * Created: 03/09/2012 04:30:01 PM
  10.  * Revision: none
  11.  * Compiler: gcc
  12.  *
  13.  * Author: Mr. He Wei Ping (hwp), hwp195@gmail.com
  14.  * Company:
  15.  *
  16.  * =====================================================================================
  17.  */
    1. #ifndef SINGLE_LINK_H
    2. #define SINGLE_LINK_H

    3. typedef struct node{
    4.     int data;
    5.     struct node *pNext;
    6. }node_t;

    7. node_t *make_node(int value);
    8. node_t *insert(node_t *head, node_t *node);
    9. node_t *invert(node_t *head);


    10. #endif
    11. ~
    12. ~
  18. #include <stdlib.h>
  19. #include "single_link.h"

  20. node_t *make_node(int value)
  21. {
  22.     node_t *p = (node_t *)malloc(sizeof(node_t));
  23.     if(p)
  24.     {
  25.         p->data = value;
  26.         p->pNext = NULL;
  27.     }
  28.     return p;
  29. }

  30. node_t *insert(node_t *head, node_t *node)
  31. {
  32.     node->pNext = head;
  33.     head = node;
  34.     return head;
  35. }

  36. node_t *invert(node_t *head)
  37. {
  38.     node_t *prev, *cur, *next;

  39.     if(head == NULL || head->pNext == NULL)
  40.         return head;

  41.     prev = head;
  42.     cur = next = head->pNext;
  43.     while(cur)
  44.     {
  45.         next = cur->pNext;
  46.         cur->pNext = prev;
  47.         prev = cur;
  48.         cur = next;
  49.     }
  50.     head->pNext = NULL;
  51.     head = prev;
  52.     return head;
  53. }

  54. void show(node_t *head)
  55. {
  56.     node_t *p = head;
  57.     while(p)
  58.     {
  59.         printf("--%d--\n", p->data);
  60.         p = p->pNext;
  61.     }
  62. }
  63. #ifdef DEBUG
  64. int main(void)
  65. {
  66.     int i;
  67.     node_t *head = NULL;

  68.     for(i = 0; i < 3; i ++)
  69.     {
  70.         head = insert(head, make_node(i+1));
  71.     }
  72.     show(head);
  73.     show(invert(head));
  74.     return 0;
  75. }
  76. #endif
阅读(395) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~