thieumao

Đảo ngược chuỗi bằng sử dụng stack

Jun 13th, 2013
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.91 KB | None | 0 0
  1. // Compiler gcc with Code::Block
  2.  
  3. #include <stdio.h>
  4.  
  5. struct node {
  6.     char ch;
  7.     struct node *next;
  8. };
  9.  
  10. typedef struct node* NODEPTR;
  11.  
  12. void Init(NODEPTR *plist) {
  13.     *plist = NULL;
  14. }
  15.  
  16. int Empty(NODEPTR plist) {
  17.     if (plist == NULL )
  18.         return 1;
  19.     return 0;
  20. }
  21.  
  22. void Push(NODEPTR *plist, char chr) {
  23.     NODEPTR p = (NODEPTR) malloc(sizeof(struct node));
  24.     p->ch = chr;
  25.     p->next = NULL;
  26.     if (Empty(*plist))
  27.         *plist = p;
  28.     else {
  29.         p->next = *plist;
  30.         *plist = p;
  31.     }
  32. }
  33.  
  34. void Pop(NODEPTR *plist, char *chr) {
  35.     if (!Empty(*plist)) {
  36.         NODEPTR p = *plist;
  37.         *plist = (*plist)->next;
  38.         *chr = p->ch;
  39.         free(p);
  40.     }
  41. }
  42.  
  43. int main() {
  44.     NODEPTR p;
  45.     Init(&p);
  46.     char st[100];
  47.     printf(" - Enter string: ");
  48.     gets(st);
  49.     int i, n = strlen(st);
  50.  
  51.     for (i = 0; i < n; i++)
  52.         Push(&p, st[i]);
  53.     for (i = 0; i < n; i++)
  54.         Pop(&p, &st[i]);
  55.  
  56.     st[n] = '\0';
  57.  
  58.     printf(" - New string: %s", st);
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment