Chinaunix首页 | 论坛 | 博客
  • 博客访问: 236067
  • 博文数量: 35
  • 博客积分: 791
  • 博客等级: 军士长
  • 技术积分: 510
  • 用 户 组: 普通用户
  • 注册时间: 2012-09-05 16:56
文章分类
文章存档

2013年(7)

2012年(28)

我的朋友

分类: C/C++

2012-09-20 08:12:15

程序要求:
实现链表的逆序,及简单的链表操作说明(如链表的创建,删除、打印等操作)。
具体代码如下:
点击(此处)折叠或打开
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. struct node
  4. {
  5.     int data;
  6.     struct node *next;
  7. };

  8. struct node *create_list(void)
  9. {
  10.     struct node *head;

  11.     head = (struct node *)malloc(sizeof(struct node));
  12.     head->next = NULL;

  13.     return head;
  14. }

  15. void insert_list(struct node *head, int data)
  16. {
  17.     struct node *new;

  18.     new = (struct node *)malloc(sizeof(struct node));
  19.     new->data = data;

  20.     new->next = head->next;
  21.     head->next = new;

  22.     return ;
  23. }

  24. void print_list(struct node *head)
  25. {
  26.     struct node *p = head->next;

  27.     while(p != NULL)
  28.     {
  29.         printf("%d ", p->data);
  30.         p = p->next;
  31.     }

  32.     printf("\n");

  33.     return ;
  34. }

  35. int reserve_list(struct node *head)
  36. {
  37.     struct node *pe = NULL;
  38.     struct node *ps = head->next;

  39.     head->next = NULL;

  40.     while(ps != NULL)
  41.     {
  42.         pe = ps->next;
  43.         ps->next = head->next;
  44.         head->next = ps;
  45.         ps = pe;
  46.     }

  47.     return 0;
  48. }

  49. int main(int argc, const char *argv[])
  50. {
  51.     int i = 0;
  52.     struct node *head;

  53.     head = create_list();

  54.     for (i = 0; i < 10; i++)
  55.         insert_list(head, i);
  56.     
  57.     print_list(head);
  58.     reserve_list(head);
  59.     print_list(head);

  60.     return 0;
  61. }


阅读(4161) | 评论(0) | 转发(5) |
给主人留下些什么吧!~~