算法:实现链表存储的回文字符串判断

题目:如何判断一个单链表结构的字符串是否是回文字符串。例如,“123454321”,返回“yes”;“12345”,返回“false”

可执行代码:isPalindrome.cpp

#include<iostream>  
#include<stack> 
#include<stdlib.h>
using namespace std;  
  
typedef struct node{  
    int data;  
    struct node *next;  
}LinkNode, *LinkList;  

class Solution {
	public: 
	void create_list(LinkList *L, int *a, int n) {  
	    int i = 0;  
	    LinkNode *p = NULL;  
	    LinkNode *temp = NULL;  
	    while(i < n) {  
	        p = (LinkNode*)malloc(sizeof(LinkNode));  
	        p->data = a[i];  
	        p->next = NULL;  
	        if(*L == NULL) {  
	            *L = p;  
	        } else {  
	            temp->next = p;  
	        }  
	        temp = p;  
	        i++;  
	    }  
	}  
	// 判断回文字符串,使用栈实现逆序 
	int isPalindrome(LinkList head) {  
	    int length = 0;  
	    int mid = 0;  
	    int i;  
	    stack<LinkNode*> m_stack;  
	    LinkNode *p = head;  
	    LinkNode *temp = NULL;  
	    int flag = 1;  
	    while(p) {  
	        length++;  
	        p = p->next;  
	    }  
	    if(length %2 == 0) {  
	        mid = length / 2;  
	    } else {  
	        mid = length / 2 + 1;  
	    }  
	    p = head;  
	    i = 1;  
	    while(i <= mid - 1) {  
	        m_stack.push(p);  
	        p = p->next;  
	        i++;  
	    }  
	    if(length % 2 == 0) {  
	        m_stack.push(p);  
	    }  
	    p = p->next;  
	    while(!m_stack.empty() && p) {  
	        temp = m_stack.top();  
	        m_stack.pop();  
	        if(temp->data != p->data) {  
	            flag = 0;  
	            break;  
	        }  
	        p = p->next;  
	    }  
	    return flag;  
	}  
};
  
int main() {  
    int a[] = {1, 2, 3, 4, 5, 4, 3, 2, 1};  
    int n = sizeof(a) / sizeof(int);  
    LinkList head = NULL; 
	Solution S; 
    S.create_list(&head, a, n);  
    if(S.isPalindrome(head)) {  
        cout << "yes" << endl;  
    } else {  
        cout << "no" << endl;  
    }  
    return 0;
}  
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读