Chinaunix首页 | 论坛 | 博客
  • 博客访问: 90494
  • 博文数量: 50
  • 博客积分: 1086
  • 博客等级: 少尉
  • 技术积分: 420
  • 用 户 组: 普通用户
  • 注册时间: 2011-10-25 16:16
文章分类
文章存档

2011年(50)

我的朋友

分类: C/C++

2011-11-15 19:44:32

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. #define LINK_LENGTH 15

  4. typedef struct _Node
  5. {
  6.     int data;
  7.     struct _Node *next;
  8. }Node, *NodePtr;

  9. void CreateLinklist(NodePtr pHead)
  10. {
  11.     NodePtr pPrev, pCurr;
  12.     int i = 0;
  13.     pPrev = pHead;
  14.     for(i = 0; i < LINK_LENGTH; i++)
  15.     {
  16.         pCurr = (NodePtr)malloc(sizeof(Node));
  17.         pCurr->data = i + 1;
  18.         pCurr->next = NULL;
  19.         pPrev->next = pCurr;
  20.         pPrev = pCurr;
  21.     }
  22. }

  23. void ReverseLinklist(NodePtr pHead)
  24. {
  25.     NodePtr pCurr, pTmp;

  26.     pCurr = pHead->next;
  27.     pHead->next = NULL; // Empty the original linklist
  28.     while(pCurr != NULL)
  29.     {
  30.         pTmp = pCurr->next;
  31.         // Insert to head
  32.         pCurr->next = pHead->next;
  33.         pHead->next = pCurr;
  34.         pCurr = pTmp;
  35.     }
  36. }

  37. void PrintLinklist(NodePtr pHead)
  38. {
  39.     NodePtr pCurr = pHead->next;

  40.     while(pCurr != NULL)
  41.     {
  42.         printf("%d ", pCurr->data);
  43.         pCurr = pCurr->next;
  44.     }
  45.     printf("\n");
  46. }

  47. int main()
  48. {
  49.     NodePtr pHead = NULL;
  50.     pHead = (NodePtr)malloc(sizeof(Node));
  51.     pHead->data = -1; // Head always not in real linklist.
  52.     pHead->next = NULL;
  53.     CreateLinklist(pHead);

  54.     printf("Original Linklist: ");
  55.     PrintLinklist(pHead);

  56.     // Reverse
  57.     ReverseLinklist(pHead);
  58.     printf("Reversed Linklist: ");
  59.     PrintLinklist(pHead);

  60.     system("pause");
  61.     return 0;
  62. }
阅读(656) | 评论(0) | 转发(0) |
0

上一篇:结构体指针用法

下一篇:合并链表排序

给主人留下些什么吧!~~