现在的位置: 首页 > 综合 > 正文

【数据结构_链表_最小堆】 链表找环,链表找交点,合并有序链表

2018年04月12日 ⁄ 综合 ⁄ 共 1046字 ⁄ 字号 评论关闭

Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

对链表反序: while(p) { q=p->next; p->next=f; f=p;p=q;}

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *p=head,*q,*f=NULL;
        while(p){//对链表反序,如果p回到起点,则有环
            q=p->next;
            p->next=f;
            f=p;p=q;
            if(p==head) return true;//有环
        }
        return false;//沒有环,p到了NULL
    }
};

合并有序链表

用优先队列(小顶堆)

class Solution {
public:
    struct cmp{
        bool operator () ( const pair<int, int> &a, const pair<int, int > &b){
            return a.first >= b.first;
        }
    }cc;
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        priority_queue<pair<int, int>, vector<pair<int, int> >, cmp> que;
        for(int i=0; i<lists.size(); i++) if(lists[i]) 
            que.push(pair<int, int>(lists[i]->val, i));
        
        ListNode *head =NULL, *tail =NULL;
        while(!que.empty()){
            pair<int, int> t = que.top(); que.pop();
            int i = t.second;
            if(!head) head = lists[i];
            else tail -> next = lists[i];
            tail = lists[i];
            lists[i] = lists[i]->next;
            if(lists[i]) 
                que.push(pair<int, int>(lists[i]->val, i));
        }
        
        if(tail) tail->next = NULL;
        
        return head;
    }
};

抱歉!评论已关闭.