链栈的基本操作API

2120阅读 0评论2015-09-19 九阳神功爱喝茶
分类:C/C++

明年就要找工作了,研二也基本没啥多的事情可做,就趁此机会好好复习数据结构和算法,将来找个好工作。以前也学过Java,但是考虑到研究生研究了一年Linux,大部分时候写的代码也是C语言的,所以此次所有的代码都用C语言完成,尽管比较难,但是相信自己能够坚持下来,我的计划是先完成数据结构上的一些基本API,亲自手写,绝不眼高手低,这是我自己写的一些基本的链栈的API:

点击(此处)折叠或打开

  1. #pragma warning(disable:4996)
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. typedef int ElemType;
  5. typedef struct stacknode {
  6.     ElemType elem;
  7.     struct stacknode* next;
  8. }stacknode, *stack;
  9. //初始化
  10. void InitLinkStack(stack *stack) {
  11.     *stack = (stacknode*)malloc(sizeof(stacknode));
  12.     stacknode* node = (stacknode*)malloc(sizeof(stacknode));
  13.     node = NULL;
  14.     (*stack)->next = node;
  15. }
  16. //建栈
  17. void CreateLinkStack(stack *stack) {
  18.     ElemType data;
  19.     scanf("%d", &data);
  20.     if (data)
  21.     {
  22.         stacknode* node = (stacknode*)malloc(sizeof(stacknode));
  23.         node->elem = data;
  24.         node->next = (*stack)->next;
  25.         (*stack)->next = node;
  26.         CreateLinkStack(&((*stack)->next));
  27.     }
  28. }
  29. //栈的遍历
  30. void TraversalLinkStack(stack stack) {
  31.     while (stack->next != NULL) {
  32.         printf("%d ", (stack->next->elem));
  33.         stack = stack->next;
  34.     }
  35. }
  36. //栈反向输出
  37. void InvertedLinkList(stack stack) {
  38.     if (stack->next->next) {
  39.         InvertedLinkList(stack->next);
  40.     }
  41.     printf("%d ", (stack->next->elem));
  42. }
  43. //入栈操作
  44. void PushLinkStack(stack *stack, ElemType elem) {
  45.     stacknode* node = (stacknode*)malloc(sizeof(stacknode));
  46.     node->elem = elem;
  47.     node->next = (*stack)->next;
  48.     (*stack)->next = node;
  49. }
  50. //出栈操作
  51. void PopLinkStack(stack *stack, ElemType *elem) {
  52.     //printf("%d ", (*stack)->next->elem);
  53.     *elem = (*stack)->next->elem;
  54.     if ((*stack)->next != NULL) {
  55.         (*stack)->next = (*stack)->next->next;
  56.     }
  57. }
  58. //取栈顶元素
  59. ElemType getStackTopElem(stack stack) {
  60.     return stack->next->elem;
  61. }

  62. int main(void) {
  63.     ElemType elem;
  64.     stack stack;
  65.     InitLinkStack(&stack);
  66.     CreateLinkStack(&stack);
  67.     PushLinkStack(&stack, 4);
  68.     //TraversalLinkStack(stack);
  69.     //PopLinkStack(&stack, &elem);
  70.     //TraversalLinkStack(stack);
  71.     //printf("%d ", elem);
  72.     InvertedLinkList(stack);
  73.     return 0;
  74. }
上一篇:迷宫问题的回溯与递归
下一篇:Hostapd工作流程分析