链表、队列、栈的相关应用(一)链表的回文结构

最近在对学习的链表、队列、栈等进行学习与总结,将遇到的题目总结出来,供大家交流

知识点:链表、栈

题目:

对于一个链表,,判断其是否为回文结构。

给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {

}

};


思路:

1.利用快慢指针,快指针每次进两格,慢指针每次进一格,当快指针指到NULL末尾时,慢指针指到中间位置

2.逆序指针

3.从头尾指针进行比较


代码:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
    bool chkPalindrome(ListNode* A) {
        // write code here
      
        if(A->next == NULL)//只有一个元素为回文
            return true;
        else if(A == NULL)//空元素不是回文
            return false; 
        //快慢指针找出中间节点
        ListNode *fast = A;//均指向头结点
        ListNode *slow = A;
        ListNode *temp, *cur;
        while(fast->next != NULL && fast != NULL) //保证fast的下下个节点不为空
        {
           // temp = slow; // temp 是保存slow的前一个节点,即第一部分的最后一个节点
            fast = fast->next->next;
            slow = slow->next;// 为奇数,slow为中间节点,偶数时,slow为第二部分第一个节点
        }//跳出程序的时候slow为中间节点
        
        cur = slow->next;
        slow ->next = NULL;
        
        //反转链表
        while(cur!=NULL)  
          {  
            temp = cur->next;      //mid,cur,temp三个指针操作反转链表。  
            cur->next = slow;  
            slow = cur;  
            cur = temp;  
          } 
        while(A != NULL && slow != NULL)  
            {  
            if(A->val == slow->val)  
                {  
                A = A->next;  
                slow = slow->next;  
            }  
            else
                return false;  
        } 
        return true;
    }
   

思路2:复制链表A,将链表中的元素通过push压入栈,再利用出栈,比较stack.top()(尾部元素) 和链表A(头部元素)是否相等

代码:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {  
public:  
    bool chkPalindrome(ListNode* A) { 
        if(A==NULL)
            return true;
        ListNode *B ;
        B = A;
        stack<int> st;


        while(B != NULL)
        {
            st.push(B->val);
            B = B->next;
        }
        
        while(A != NULL)
        {
            if(st.top() == A->val)
            {
                st.pop();
                A = A->next;
            }
            else 
                return false;
        }
        return true;
    }
};



猜你喜欢

转载自blog.csdn.net/haikuotiankong7/article/details/78664165