字符串回文判断, 链表回文判断

来源:互联网 发布:伊芙蕾雅淘宝店 编辑:程序博客网 时间:2024/06/07 03:56



字符串回文判断, 链表回文判断

描述: 

判断一个字符串是否是回文

判断一个链表是否是回文:


  写这个的主要目的是对基本数据结构的使用,对编程初学者来说也是一个很好的练习


很简单,上代码:

#include<iostream>#include<string.h>using namespace std;int  func(char *arr , int low , int high , int length){    //╣щ╧И╥╫й╫й╣ож    if(length == 0 || length ==1)    {        return 1;    }    if(arr[low] != arr[high])        return 0;    return func(arr, low+1, high-1, length-2);}int main(){//   char *arr;    //char    arr[]="aaabdaaa";    char arr[1000]; //="aaabbaaa";    while(cin>>arr)    {        int length = strlen(arr);        int ans = func(arr, 0, length-1, length);        if(ans)        {            cout<<"Yes!"<<endl;        }        else        {            cout<<"No!"<<endl;        }    }    return 0;}



再上代码:

#include<iostream>#include<vector>#include<stack>using namespace std;struct ListNode{    int key;    ListNode* next;    ListNode(int x) : key(x), next(NULL) {}};class PalindromeList{public:    bool chkPalindrome(ListNode* A)    {//        // write code here//        stack<int> s;//        ListNode* cur=A;//        while(cur)//        {//            s.push(cur->key);//            cur=cur->next;//        }//        while(A)//        {//            if(s.top()!=A->key)//            {//                return false;//            }//            s.pop();//            A=A->next;//        }//        return true;         ListNode* cur = A;         stack<int> s;         // 先逆序,然后再比较         while(cur){            s.push(cur->key);            cur = cur->next;         }         while(A){            if(s.top() != A->key){               return false;            }            A = A->next;            s.pop();         }         return true;    }};int main(){//    ListNode head = new ListNode;    ListNode* node1 =  new ListNode(1);    ListNode* node2 = new ListNode(2);    ListNode* node3 =  new ListNode(2);    ListNode* node4 =  new ListNode(1);    node1->next = node2;    node2->next = node3;    node3->next = node4;    PalindromeList M;        //用定义好的类创建一个对象 点M    bool a = M.chkPalindrome(node1); //设置 M点 的x,y值//    M.printPoint();     //输出 M点 的信息    cout<<a<<endl;    return  0;}




0 0