思路:求出链表的长度,将链表前面一般的元素入栈,然后逐个出栈与后一半的元素进行比较,如果一旦不相等立马返回FALSE,停止比较,如果到最后栈不为空也要返回FALSE,只有当栈为空且出栈的元素和链表后一半的元素都想得才能返回TRUE;另外要注意的一点是长度为1的链表都是回文链表所以要进行特殊处理,即当length=1时直接返回TRUE不用进行后续的操作。
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ typedef struct stacknode { int data; struct stacknode* next; }stacknode; int l(struct ListNode* head) { struct ListNode* p=head; int i=0; while(p!=NULL) { i++; p=p->next; } return i; } void push(struct stacknode **s,int n) { struct stacknode *p; p=(stacknode*)malloc(sizeof(stacknode)); p->data=n; p->next=(*s); (*s)=p; } int pop(struct stacknode** s) { int e=(*s)->data; (*s)=(*s)->next; return e; } int empty(struct stacknode* S) { if(S==NULL) return 0; else return 1; } bool isPalindrome(struct ListNode* head){ if(head==NULL) return false; struct stacknode* S; S=NULL; struct ListNode* p=head; int length=l(head); if(length==1) return true; for(int i=1;i<=length/2;i++) { push(&S,p->val); p=p->next; } if(length%2!=0) p=p->next; while(p!=NULL) { if(p->val==pop(&S)) p=p->next; else return false; } if(empty(S)==0&&p==NULL) return true; else return false; }
运行结果: