一、线性链表的回文数字判断
参考书:《数据结构(C语言)》–严蔚敏等编著,清华大学出版社。 相关代码:
#include "stdio.h"
#include "stdlib.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);
Status CreateList_L(LinkList &L) {
LinkList p,q;
char ch;
L = (LinkList) malloc (sizeof(LNode));
L->next = NULL;
q=L;
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);
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;
for(int n=0; n<i-1; n++) {
Pre=Pre->next;
}
LNode *Cur=Pre->next;
LNode *Next=Cur->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);
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;
}
|