69,382
社区成员
发帖
与我相关
我的任务
分享
// exercise 5, chapter 17
#include <stdio.h>
#include <stdlib.h>
typedef char Item;
typedef struct node
{
Item item;
struct node * next;
struct node * prev;
}Node;
typedef struct {
Node * head;
Node * tail;
}Stack;
int main(void)
{
char ch;
Stack stack;
Node * tmp;
stack.head = stack.tail = NULL;
puts("Enter a string:");
while((ch = getchar())!= '\n' && (ch = getchar()) != EOF)
{
tmp = (Node *) malloc(sizeof(Node));
tmp->item = ch;
if(tmp == NULL)
{
fputs("Failed to allocate memory.", stderr);
exit(1);
}
if(stack.head == NULL)
{
stack.head = tmp;
stack.head->prev = NULL; //让第一个元素的前溯指针为NULL
}
else
{
stack.tail->next = tmp;
tmp->prev = stack.tail; //让从第二个元素开始的前溯指针指向前一个元素
}
tmp->next = NULL;
stack.tail = tmp;
}
if(stack.head == NULL)
puts("No string entered.");
else
{
puts("String in reverse:");
tmp = stack.tail;
while(tmp != NULL)
{
putchar(tmp->item);
tmp = tmp->prev;
}
}
puts("\nDone!");
return 0;
}
// exercise 5, chapter 17
#include <stdio.h>
#include <stdlib.h>
typedef char Item;
typedef struct node
{
Item item;
struct node * next;
struct node * prev;
}Node;
typedef struct {
Node * head;
Node * tail;
}Stack;
int main(void)
{
char ch;
Stack stack;
Node * tmp;
stack.head = stack.tail = NULL;
puts("Enter a string:");
while((ch = getchar())!= '\n' && (ch = getchar()) != EOF) //我找到了,是这里出了问题
{ //(ch = getchar()) != EOF是多读了字符了
tmp = (Node *) malloc(sizeof(Node));
tmp->item = ch;
if(tmp == NULL)
{
fputs("Failed to allocate memory.", stderr);
exit(1);
}
if(stack.head == NULL)
{
stack.head = tmp;
stack.head->prev = NULL; //让第一个元素的前溯指针为NULL
}
else
{
stack.tail->next = tmp;
tmp->prev = stack.tail; //让从第二个元素开始的前溯指针指向前一个元素
}
tmp->next = NULL;
stack.tail = tmp;
}
if(stack.head == NULL)
puts("No string entered.");
else
{
puts("String in reverse:");
tmp = stack.tail;
while(tmp != NULL)
{
putchar(tmp->item);
tmp = tmp->prev;
}
}
puts("\nDone!");
return 0;
}
typedef struct node
{
int num;
struct node *next;
}NODE;
struct node *crfun(int n)
{
NODE* head=NULL;
NODE* p;
while(n)
{
p=(NODE*)malloc(sizeof(NODE));
scanf("%d",&p->num);
p->next=head;
head=p;
n--;
}
return p;
}