参考书:《数据结构(C语言)》–严蔚敏等编著,清华大学出版社。
相关代码:
#include "stdio.h" #include "stdlib.h" //#include "linkList.h" #define OK 1 #define ERROR 0 #define TRUE 1 #define FLASE 0 #define OVERFLOW -2 typedef int Status; typedef int ElemType; typedef struct LNode { ElemType data; //数据域(信息域) struct LNode *next; //指针域 } LNode, *linkList; Status CreateList_L(linkList &L); //构造有头结点的链表L Status CreateList_L(linkList &L) { linkList p,q; char ch; L = (linkList) malloc (sizeof(LNode)); L->next = NULL; q=L; //起初为L(头)---->NULL while((ch=getchar()) != 'n') { p = (linkList) malloc (sizeof(LNode)); p->data = ch; p->next = NULL; q->next = p; q = q->next; } return OK; } Status ListTrans_L(linkList &L,int i); //在链表L中从第 i 个位置起进行元素转置 Status ListTrans_L(linkList &L,int i) { if(i<=0) return ERROR; linkList trans = (linkList) malloc (sizeof(LNode)); if(!trans) exit(OVERFLOW); trans=L; LNode *Pre=trans; //Pre为前驱,指向新头结点 for(int n=0; nnext; //指针后移直至指向i-1处 } LNode *Cur=Pre->next; //记录当前Cur LNode *Next=Cur->next; //记录后继Next while(Next!=NULL) { Cur->next = Next->next; Next->next = Pre->next; Pre->next = Next; Next = Cur->next; } return OK; } Status ListPalinDrome_L(linkList L); //判断链表L中存储的数据是否为回文 Status ListPalinDrome_L(linkList L) { linkList p,fast,mid,slow; int i=1; fast=L; slow=L; while(fast->next && fast->next->next) { fast = fast->next->next; slow = slow->next; i++; } ListTrans_L(L,i); //从中间位置转置,进行前截与后截判断 mid = slow->next; p = L->next; slow = slow->next; while(p!=mid) { if(p->data == slow->data) { p=p->next; slow=slow->next; } else { printf("非回文"); return ERROR; } } printf("回文"); return OK; } int main(void) { linkList L; CreateList_L(L); ListPalinDrome_L(L); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)