C语言:输出一串字符,判断是否是"回文"
使用单链表
#include
#include
typedef struct _TNode
{
char c;
struct _TNode *next;
}
TNode;
void push(TNode **ppStack, TNode *pNode)
{
pNode->next = *ppStack;
*ppStack = pNode;
}
TNode *pop(TNode **ppStack)
{
TNode *pRet = *ppStack;
if (pRet)
{
*ppStack = pRet->next;
}
return pRet;
}
TNode *create_node(...全部
使用单链表
#include
#include
typedef struct _TNode
{
char c;
struct _TNode *next;
}
TNode;
void push(TNode **ppStack, TNode *pNode)
{
pNode->next = *ppStack;
*ppStack = pNode;
}
TNode *pop(TNode **ppStack)
{
TNode *pRet = *ppStack;
if (pRet)
{
*ppStack = pRet->next;
}
return pRet;
}
TNode *create_node(char c)
{
TNode *pNew = (TNode *)malloc(sizeof(TNode));
pNew->c = c;
pNew->next = NULL;
return pNew;
}
bool huiwen(TNode *pList)
{
TNode *p1 = pList, *p2 = pList, *pStack = NULL, *pQueue = NULL;
for (; p2 && p2->next; p1 = p1->next, p2 = p2->next, p2 = p2->next)
{
push(&pStack, create_node(p1->c));
}
if (p2)
{
pQueue = p1->next;
}
else
{
pQueue = p1;
}
for (p1 = pStack, p2 = pQueue; p2; p1 = p1->next, p2 = p2->next)
{
if (p1->c != p2->c)
{
break;
}
}
while (pStack)
{
free(pop(&pStack));
}
if (p2)
{
return false;
}
return true;
}
int main()
{
TNode *pList = NULL, *pWork;
TNode **ppTail = &pList;
char *pcTmp;
char szBuf[256];
printf("input a string:\n");
scanf("%255s", szBuf);
for (pcTmp = szBuf; *pcTmp; pcTmp++)
{
push(ppTail, create_node(*pcTmp));
ppTail = &(*ppTail)->next;
}
printf("create a list with value:\n");
for (pWork = pList; pWork; pWork = pWork->next)
{
printf("%c", pWork->c);
}
printf("\n");
if (huiwen(pList))
{
printf("Yes, it's a huiwen string!\n");
}
else
{
printf("No, it's not a huiwen string!\n");
}
while (pList)
{
free(pop(&pList));
}
fgets(szBuf, 256, stdin);
getchar();
return 0;
}
。
收起