迴文鏈表和鏈表排序

迴文鏈表

思路:找到鏈表的中間節點然後前面一部分進行逆置,變成兩個鏈表,然後將值逐個進行比較

樣例
Input: 1->2->2->1
Output: true

class Solution {
public:
    bool isPalindrome(ListNode* head) {
        int lenth, i;
        ListNode *point1, *point2, *point3;
        point3 = point2 = head;
        point1 = NULL;
        lenth = 0;
        if(head == NULL || head->next == NULL)
            return true;
        while(point3 != NULL)//取得長度
        {
            point3 = point3->next;
            lenth++;
        }
        for(i = 0;i < (lenth / 2);i++)//遍歷到中間,並逆置
        {
            point3 = point2->next;
            point2->next = point1;
            point1 = point2;
            point2 = point3;
        }
        if((lenth % 2) == 1)
            point3 = point3->next;
        while(point3 != NULL && point1 != NULL)//兩個指針開始向兩頭移動,取值比較
        {
            if(point3->val != point1->val)
                return false;
            point3 = point3->next;
            point1 = point1->next;
        }
        return true;//比較中沒有發現不同值,則爲迴文鏈表
    }
};

鏈表排序

思路找到鏈表的中間點,將鏈表分開,讓這兩個鏈表分別有序,最後進行合併
歸併排序+鏈表

 ListNode* sortList(ListNode* head) {
         if(!head || !head->next) return head;
        
        ListNode *slow = head,*fast = head;
        while(fast && fast->next && fast->next->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        
        ListNode *p1 = head,*p2 = slow->next;
        slow->next = nullptr;
        
        p1 = sortList(p1);
        p2 = sortList(p2);
        
        ListNode node(0),*head1 = &node;
        while(p1 && p2)
        {
            if(p1->val < p2->val)
            {
                head1->next = p1;
                head1 = p1;
                p1 = p1->next;
            }
            else{
                head1->next = p2;
                head1 = p2;
                
                p2 = p2->next;
            }
        }
        
        if(p1)
            head1->next = p1;
        if(p2)
            head1->next = p2;
        
        return node.next;
    }
};

方法二
堆排序+鏈表
記住如何在用優先隊列創建一個小根堆並且裏面存儲的是鏈表的節點

class Solution {
public:
    static bool cmp(ListNode* p1,ListNode* p2)
    {
        return p1->val>p2->val;
    }
    ListNode* sortList(ListNode* head) {
        priority_queue<ListNode*,vector<ListNode*>,decltype(cmp)*>  q(cmp);
        ListNode* p=head;
        while(p)
        {
            q.push(p);
            p=p->next;
        }
        auto dummy=new ListNode(-1);
        ListNode* cur=dummy;
        while(q.size())
        {
            ListNode* temp=q.top();
            q.pop();
            cur->next=temp;
            cur=cur->next;
        }
        cur->next=nullptr;
        return dummy->next;      
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章